我有一个带有几个控件的usercontrol。因此,我决定使用ViewModel来管理所有这些可绑定值。但是我发现绑定始终为空。那么如何在用户控件中为ViewModel设置绑定
MainWindows.xaml
<Window x:Class="Test.MainWindow"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<cus:Wizard WizardModel="{Binding MyModel}"/>
</StackPanel>
</Window>
MainWindows.xaml.cs
public partial class MainWindow : Window
{
private ViewModel vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = vm;
}
}
ViewModel.cs(MainWindow viewmodel)
public class ViewModel : INotifyPropertyChanged
{
private Model _MyModel;
public Model MyModel
{
get
{
return _MyModel;
}
set
{
_MyModel = value;
NotifyPropertyChanged("MyModel");
}
}
}
Wizard.xaml(我的用户控件)
<UserControl mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Something}" />
</Grid>
</UserControl>
Wizard.xaml.cs
public partial class Wizard : UserControl
{
private readonly object modelLock = new object();
private Model CurrentModel = new Model();
public Wizard()
{
InitializeComponent();
DataContext = CurrentModel;
}
public Model WizardModel
{
get { return (Model)this.GetValue(WizardModelProperty); }
set { this.SetValue(WizardModelProperty, value); }
}
public static readonly DependencyProperty WizardModelProperty = DependencyProperty.Register("WizardModel", typeof(Model), typeof(Wizard), new PropertyMetadata(null, new PropertyChangedCallback(ModelChanged)));
private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Wizard)d).OnModelChanged();
}
private void OnModelChanged()
{
lock (this.modelLock)
{
if(CurrentModel != null)
{
CurrentModel = null;
}
if (WizardModel != null)
{
CurrentModel = WizardModel;
}
}
}
}
UserControl中的WizardModel始终为null。那么如何在UserControl中设置此ViewModel
答案 0 :(得分:0)
应该在特定视图模型类上或更确切地说在具有特定公共属性集的类上运行的UserControl可以直接绑定到其XAML中的视图模型属性。
给出类似的视图模型
public class Model
{
public string Something { get; set; }
}
您可以仅使用此XAML编写UserControl
<UserControl ...>
...
<TextBox Text="{Binding Something}" />
...
</UserControl>
以及后面的代码
public partial class Wizard : UserControl
{
public Wizard()
{
InitializeComponent();
}
}
如果您现在将其DataContext设置为Model
的实例(或任何其他具有Something
属性的类),它将可以正常工作:
<local:Wizard DataContext="{Binding MyModel}"/>
由于DataContext属性的值是从父元素继承到子元素,因此这也将起作用:
<StackPanel DataContext="{Binding MyModel}">
<local:Wizard/>
</StackPanel>
但是,UserControl仍然依赖于其DataContext中Something
属性的存在。为了摆脱这种依赖性,您的控件可能会公开一个依赖性属性
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register(nameof(MyText), typeof(string), typeof(Wizard));
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
并将其XAML中的元素绑定到其自己的属性
<UserControl ...>
...
<TextBox Text="{Binding MyText,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
...
</UserControl>
现在,您将绑定控件的属性,而不是设置其DataContext:
<local:Wizard MyText="{Binding MyModel.Something, Mode=TwoWay}"/>