当前正在实现一个自定义控件,我想直接从我的 viewModel 绑定(bind)一些值,而不使用 xaml。 我可以这样做:
<customControls:MyControl MyValue="{Binding ElementName=MyElem, Path=Text}">
<Textbox Text="{Binding Mytext}" />
但不是:
<customControls:MyControl MyValue="{Binding MyText}">
控件在模板中定义,并且在控制代码中,MyProperty 定义为:
public static readonly DependencyProperty MyValueProperty = DependencyProperty.Register("MyValue", typeof(double), typeof(CustomOEE), new FrameworkPropertyMetadata((Double)20,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public double MyValue
{
get
{
return (double)GetValue(MyValueProperty);
}
set
{
SetValue(MyValueProperty, value);
}
}
非常感谢您的帮助
最佳答案
作为一般答案,在 UserControl 中,您仅绑定(bind)到 UserControl DependencyProperties,并使用 ElementName 或relativeSource 绑定(bind)来执行此操作,并且您不应该永远在 UserControl 中设置 DataContext。
public static readonly DependencyProperty MyOwnDPIDeclaredInMyUcProperty =
DependencyProperty.Register("MyOwnDPIDeclaredInMyUc",
typeof(string), typeof(MyUserControl));
public string MyOwnDPIDeclaredInMyUc
{
get
{
return (string)GetValue(MyOwnDPIDeclaredInMyUcProperty);
}
set
{
SetValue(MyOwnDPIDeclaredInMyUcProperty, value);
}
}
xaml
<UserControl x:Name="myRealUC" x:class="MyUserControl">
<TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Mode=TwoWay}"/>
<UserControl>
如果您这样做,您可以在任何 View 中轻松使用此用户控件,例如:
<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>
关于wpf - 自定义控件数据绑定(bind) wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916756/