XAML 对象初始值设定项如何与 CLR 属性配合使用?
如果我需要创建与以下内容等效的 XAML:
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
那么就会是:
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
但是如果我想要这样的东西:
public string KeyFieldView { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel()
{
KeyFieldVM=KeyFieldView
};
}
我能够到达 KeyFieldVM=""
,但不确定如何访问 KeyFieldView。
<Window.DataContext>
<vm:MainWindowViewModel KeyFieldVM=""/>
</Window.DataContext>
最佳答案
您可以绑定(bind) KeyFieldVM
属性,前提是它是依赖属性:
public class MainWindowViewModel : DependencyObject
{
public static readonly DependencyProperty KeyFieldVMProperty =
DependencyProperty.Register("KeyFieldVM", typeof(string),
typeof(MainWindowViewModel), new FrameworkPropertyMetadata("ok"));
public string KeyFieldVM
{
get { return (string)GetValue(KeyFieldVMProperty); }
set { SetValue(KeyFieldVMProperty, value); }
}
}
<Window ... x:Name="win">
<Window.DataContext>
<vm:MainWindowViewModel KeyFieldVM="{Binding KeyFieldView, ElementName=win}"/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding KeyFieldVM}" />
</Grid>
</Window>
这要求 View 模型是DependencyObject
,但这有其缺点:
INotifyPropertyChanged vs. DependencyProperty in ViewModel
XAML 是标记语言。它没有任何变量的概念,所以你不能做这样的事情:
<vm:MainWindowViewModel KeyFieldVM="{this.KeyFieldView}"/> <!-- BAD MARKUP -->
如果您想这样做,您应该以编程方式创建 View 模型,例如在 View 的代码隐藏中。
关于c# - XAML 中的对象初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42156862/