Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将自定义控件的依赖项属性绑定到其视图模型属性_C#_Wpf_Mvvm_Binding_Viewmodel - Fatal编程技术网

C# 如何将自定义控件的依赖项属性绑定到其视图模型属性

C# 如何将自定义控件的依赖项属性绑定到其视图模型属性,c#,wpf,mvvm,binding,viewmodel,C#,Wpf,Mvvm,Binding,Viewmodel,我正在尝试将自定义控件的依赖项属性绑定到其ViewModel属性 自定义控件看起来像: 视图模型如下所示: 由于某种原因,“Text”属性的绑定不起作用 我试图做的是,在实际实现中,我希望在更新基础ViewModel的text属性时更新MyCustom控件的text属性 非常感谢您的帮助。只需绑定到dependency属性即可 <MyCustomControl Text="{Binding Path=Text}" /> 您应该将您的成员TextBox绑定到您的TextPro

我正在尝试将自定义控件的依赖项属性绑定到其ViewModel属性

自定义控件看起来像:



视图模型如下所示:


由于某种原因,“Text”属性的绑定不起作用

我试图做的是,在实际实现中,我希望在更新基础ViewModel的text属性时更新MyCustom控件的text属性


非常感谢您的帮助。

只需绑定到dependency属性即可

<MyCustomControl Text="{Binding Path=Text}" />


您应该将您的成员TextBox绑定到您的TextProperty。我敢肯定,文本属性上的xaml绑定会覆盖构造函数中的绑定。

经过一些研究,我终于找到了代码的问题所在。我通过创建一个静态事件处理程序来实现这段代码,该处理程序实际上将新属性值设置为dependency属性的底层公共成员。依赖项属性声明类似于:

//Dependency Property
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyCustomControl), new PropertyMetadata(null, OnTextChanged));
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyCustomControl myCustomControl = (MyCustomControl)d;
    myCustomControl.Text = (string) e.NewValue;
}
然后定义设置属性的静态方法,如下所示:

//Dependency Property
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyCustomControl), new PropertyMetadata(null, OnTextChanged));
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyCustomControl myCustomControl = (MyCustomControl)d;
    myCustomControl.Text = (string) e.NewValue;
}
这是我唯一缺少的东西


干杯

显示您正在使用的xaml绑定。似乎这应该可以,请在文本中设置一个断点Setter@eranotzer:我尝试在文本设置器上放置断点,但它从未触及视图中的设置器,属性未绑定到基础viewmodels属性的原因。@MichaelG:视图中没有xaml绑定,因为所有控件都是动态生成的。视图的Xaml非常小:'@MichaelG:但是使用控件的Xaml看起来像:''我在代码中确认控件的datacontext属性成功绑定到MyCustomControlVM属性,即MyCustomControlViewaModel的实例。此时无法将控件属性绑定到基础视图模型的属性。我希望将数据上下文绑定到基础视图模型,然后我希望控件属性绑定能够正常工作。大概是这样的:'