【问题标题】:Object initializer in XAMLXAML 中的对象初始化器
【发布时间】:2017-02-10 10:19:10
【问题描述】:

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>

【问题讨论】:

  • 这就是为什么 MS 让我如此生气。您所要求的在 XAML-2009 中是微不足道的,但 WPF 仅支持 XAML 的原始版本。

标签: c# .net wpf xaml


【解决方案1】:

您可以绑定 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>

这要求视图模型是DependencyObject,但这有其缺点:

INotifyPropertyChanged vs. DependencyProperty in ViewModel

XAML 是 标记 语言。它没有任何变量的概念,所以你不能这样做:

<vm:MainWindowViewModel KeyFieldVM="{this.KeyFieldView}"/> <!-- BAD MARKUP -->

如果您想这样做,您应该以编程方式创建视图模型,例如在视图的代码隐藏中。

【讨论】:

  • 尽管如此,我不必创建依赖属性来访问普通的 CLR 属性,并且可以避免绑定,但看起来这是唯一的方法
  • 任何 target 属性,即在视图中绑定 to 的属性,必须是依赖属性。
【解决方案2】:

您可以使用ObjectDataProvider 中的this answer 将构造函数参数传递给对象的实例化。但是,these parameters can't be bound。因此,您的动态属性值不能在构造函数中使用。

您必须将这些属性设为常量,并从您的 XAML 中传递它们,或者从后面的代码中填充它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多