我尝试创建一个MultiConverter,将CurrentUser的权限级别与枚举中的权限子集进行比较,以切换某些按钮的可见性。创建UserControl时,会在启动时调用我的转换器,但如果在那之后修改CurrentUser的级别,则不会再次调用转换器。
基本结构是:
KioskController拥有UserInfo拥有CurrentUser拥有Level。我正在绑定并更新CurrentUser.Level。重要片段如下:
<Image x:Name="Redeem" Height="114" Width="178" Source="GraphicsMAINMENU_Redeem.png" Margin="128,260,718,394">
<Image.Visibility>
<MultiBinding Converter="{StaticResource theIntPermissionToVisibilityConverter}">
<Binding Path="_UserInfo.CurrentUser.Level"/>
<Binding Source="{x:Static local:UserInfo+UserLevel.Cashier}"/>
<Binding Source="{x:Static local:UserInfo+UserLevel.Manager}"/>
<Binding Source="{x:Static local:UserInfo+UserLevel.Tech}"/>
</MultiBinding>
</Image.Visibility>
</Image>
KioskController:
public sealed class KC : DependencyObject
{
/// <summary>
/// Singleton interface to the Kiosk Controller
/// </summary>
///
#region _UserInfoDependencyProperty
public UserInfo _UserInfo
{
get { return (UserInfo)this.GetValue(_UserInfoProperty); }
set { this.SetValue(_UserInfoProperty, value); }
}
public static readonly DependencyProperty _UserInfoProperty = DependencyProperty.Register(
"_UserInfo", typeof(UserInfo), typeof(KC), new PropertyMetadata(null));
#endregion
UserInfo类:
public class UserInfo : DependencyObject
{
#region CurrentUserProperty
public User CurrentUser
{
get { return (User)this.GetValue(CurrentUserProperty); }
set { this.SetValue(CurrentUserProperty, value); }
}
public static readonly DependencyProperty CurrentUserProperty = DependencyProperty.Register(
"CurrentUser", typeof(User), typeof(UserInfo), new PropertyMetadata(null));
#endregion
最后是用户类:
public class User : DependencyObject
{
#region UserLevelProperty
public UserInfo.UserLevel Level
{
get { return (UserInfo.UserLevel)this.GetValue(LevelProperty); }
set { this.SetValue(LevelProperty, value); }
}
public static readonly DependencyProperty LevelProperty = DependencyProperty.Register(
"UserLevel", typeof(UserInfo.UserLevel), typeof(User), new PropertyMetadata(UserInfo.UserLevel.Invalid));
#endregion
我正在将用户控件的DataContext设置为KioskController,这似乎正在起作用。我在一个文本块中测试了一个简单的字符串绑定,结果显示不错
最后,更新CurrentUser的调用会触发Setter,但不会再次调用转换器:
CurrentUser.Level = theUser.Level;
我在控制台窗口中启用了绑定错误,并且在输出中没有看到任何问题。
据我所知,更改DependencyProperty会导致绑定到它的元素更新,但不会导致转换器重新评估。这似乎通常被认为是一个疏忽或错误。解决方案是强制重新评估转换器:
MultiBindingExpression be = BindingOperations.GetMultiBindingExpression(Redeem, Image.VisibilityProperty);
be.UpdateTarget();
或者对于单个绑定转换器:
BindingExpression be = BindingOperations.GetBindingExpression(Redeem, Image.VisibilityProperty);
be.UpdateTarget();
然而,这有点不友好,因为您的代码绑定需要知道XAML中的绑定,并使用有问题的转换器为每个对象调用此操作。如果有一个使用iNotifyPropertyChanged的解决方案,我希望看到它。
此链接帮助解决了问题:DependencyObject.InvalidateProperty不工作