c# - XAML 中的对象初始值设定项

标签 c# .net wpf xaml

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/

相关文章:

c# - 无法从 Azure Data Lake Analytics 访问 Azure Key Vault

.net - Windows 10 拖放

c# - 为 Azure Functions 创建测试项目

sql - 无法使用 MVVM 模式从数据库中显示 WPF 中的表

c# - 如何在 C# 中不提供全局/静态变量的情况下实现单例模式?

c# - 是否可以使用 oData.net 实现微服务

c# - 在 C# 中使用 ActiveX

c# - 正则表达式:匹配 JavaScript 源代码中的 'in' 运算符

c# - 如何为 WPF 数据网格中的特定列设置 StringFormat,其值通过 ItemsSource 方法填充

c# - RichTextBox (WPF) 没有字符串属性 "Text"