【问题标题】:How to databind property from view model to custom user control in WPF? [duplicate]如何将视图模型中的属性数据绑定到 WPF 中的自定义用户控件? [复制]
【发布时间】:2020-06-16 08:55:13
【问题描述】:

我创建了一个自定义控件来测试绑定的工作方式。它有一个依赖属性,我想从另一个视图绑定,并且我希望它在绑定的属性使用 INotifyPropertyChanged 引发 PropertyChanged 时更新:

public string BindLabelText
{
    get { return (string)GetValue(BindLabelTextProperty); }
    set { SetValue(BindLabelTextProperty, value); }
}

public static readonly DependencyProperty BindLabelTextProperty =
    DependencyProperty.Register("BindLabelText", typeof(string), typeof(BindingControl), 
    new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

在我的控件中,我像这样绑定依赖属性:

<TextBlock 
    Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
    Text="{Binding ElementName=TestControl, Path=BindLabelText,  FallbackValue=BindLabelText}" 
    FontSize="20"/>

我使用这样的控制:

<local:BindingControl BindLabelText="Static main window value" />
<local:BindingControl BindLabelText="{Binding HeaderLabel, FallbackValue=HeaderLabel}" />
<Button Content="Change MainWindow property" Command="{Binding ChangeMainTextCommand}"/>

TextBlock 文本值设置为静态值,但当我尝试将其绑定到属性时它不起作用。在这两个视图中,我在后面的代码中将 DataContext 设置为 ViewModel:

this.DataContext = new BindingControlViewModel();

编辑: 将我的代码添加到github。就像我在 cmets 中所说的那样,我正在尝试将 MainWindowViewModel 上的属性绑定到我的用户控件 DP BindLabelText,这是我的父视图 (MainWindow) 的 DataContext。 User Control 除了 DP 也有自己的 ViewModel。我的目标是让用户控件在来自 MainWindowViewModel 的绑定属性更新时更新。

【问题讨论】:

  • 什么是TestControl?输出窗口中是否有绑定错误?
  • TestControl 是我的自定义控件的名称。我得到:BindingExpression 路径错误:在“对象”“BindingControlViewModel”(HashCode=47044325)上找不到“HeaderLabel”属性。绑定表达式:路径=标题标签; DataItem='BindingControlViewModel' (HashCode=47044325);目标元素是“BindingControl”(名称=“TestControl”);目标属性是“BindLabelText”(类型“字符串”)。 HeaderLabel 在我的 MainWindowViewModel (我使用控件的视图)上。 BindingControlViewModel 是自定义控件 ViewModel。
  • 您使用控件的 XAML 的数据上下文是什么?如果不是 BindingControlViewModel,则需要创建绑定:&lt;local:BindingControl BindLabelText="{Binding DataContext.HeaderLabel} 并在 XAML 顶部设置数据上下文 d:DataContext="{d:DesignInstance {x:Type vm:YourViewModell}}"
  • 我使用控件的 DataContext 是 MainWindowViewModel 我想将此 ViewModel 的属性绑定到我的自定义控件 BindLabelText DP。
  • 您是否尝试过我的建议,将主视图的数据上下文设置为 MainWindowViewModel?所以在MainWindow.cs 你会有DataContext = new MainWindowViewModel();并在您的控件的代码隐藏中将其保留为DataContext = new BindingControlViewModel()。在 xaml 中将顶部的数据上下文设置为 d:DataContext="{d:DesignInstance {x:Type vm:YourViewModell}}" 并将控件上的绑定设置为 {Binding DataContext.HeaderLabel}

标签: c# wpf mvvm data-binding


【解决方案1】:

我设法通过将我的控件 DataContext 设置为像 MyGrid.DataContext = new BindingControlViewModel(); 这样的网格来解决它,而不是像 this.DataContext = new BindingControlViewModel(); 这样在控件本身上设置它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多