WPF绑定-避免间接级别

WPF绑定-避免间接级别,wpf,binding,Wpf,Binding,我正在动态填充上下文菜单,使用类似这样的类来表示每个项:- public class ContextMenuItem : INotifyPropertyChanged { public string Header {get;set;} public bool IsChecked {get;set;} public ICommand Command {get;set;} ..etc.. } 注意,这些属性实现了标准的INotifyPropertyChanged内容

我正在动态填充上下文菜单,使用类似这样的类来表示每个项:-

public class ContextMenuItem : INotifyPropertyChanged
{
    public string Header {get;set;}
    public bool IsChecked {get;set;}
    public ICommand Command {get;set;}
    ..etc..
}
注意,这些属性实现了标准的INotifyPropertyChanged内容,我在这里省略了它以节省空间

我将不包括XAML-上述属性仅绑定到它们的
MenuItem
对应项

这是我的问题。我希望菜单项的
IsChecked
状态“跟踪”另一个模型的布尔属性值。例如:-

var menuItem = new ContextMenuItem
    {
       Caption = "Online?", 
       IsChecked = user.IsOnline
    };
这显然无法正常工作-虽然菜单项的选中状态最初会反映用户的联机状态,但选中状态不会随着
user.IsOnline
的更改而更改


一种方法是订阅
用户
对象的PropertyChanged事件,并在
IsOnline
更改时对
进行更改
,但这感觉有点复杂。有更优雅的解决方案吗?

如果您将
IsChecked
a和类a dependency对象绑定在一起,您可以像这样将它们绑定在一起

 public class ContextMenuItem : DependencyObject
 {
     public static readonly DependencyProperty IsCheckedProperty = 
          DependencyProperty.Register("IsChecked", typeof(bool), typeof(ContextMenuItem ));


    public bool IsChecked
    {
        get
        {
            return this.GetValue(IsCheckedProperty) as string;
        }
        set
        {
            this.SetValue(IsCheckedProperty, value);
        }
    }
 }

 var binding = new Binding("IsOnline");
 binding.Source = user;
 binding.Mode = BindingMode.OneWay;
 BindingOperations.SetBinding(menuItem,ContextMenuItem.IsCheckedProperty,binding);

如果您的用户对象也实现了INotifyPropertyChanged,您可以在VM中公开用户并直接绑定到它

 <... IsCheck="{Binding User.IsOnline}" ... >

但是您订阅用户属性更改的方法也很有效:)有一些帮助器类可以减少锅炉代码