当我尝试将一个int值绑定到一个样式的自定义控件中的DependencyProperty时,我遇到了问题。
MyClassVM包含一个名为Number的int。当我以相同的方式绑定时,它在Label中完美显示,但不会在我的自定义控件上设置。如果我改变了" {Binding Number}"至" 15"例如,一切都适用于自定义控件。
<Style TargetType="{x:Type ItemsControl}" x:Key="TestKey">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ItemsPresenter />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Style.Resources>
<DataTemplate DataType="{x:Type local:MyClassVM}">
<StackPanel Orientation="Horizontal">
<StackPanel.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding DataContext.OpenProjectCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding .}" />
</StackPanel.InputBindings>
<ctrl:MyCustomControl Margin="5" Width="50" ctrl:MyCustomControl.ValueProperty="{Binding Number}"/>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Number}" FontSize="14" Foreground="{DynamicResource CeriseBrush}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</Style.Resources>
</Style>
这就是MyCustomControl类的外观。
public partial class MyCustomControl: CustomUserControl
{
public int Value { get { return _value; } set { _value = value; } }
public MyCustomControl()
{
InitializeComponent();
DataContext = this;
}
public string ValueProperty
{
get { return (string)GetValue(ValuePropertyProperty); }
set { SetValue(ValuePropertyProperty, value); }
}
public static readonly DependencyProperty ValuePropertyProperty =
DependencyProperty.Register("ValueProperty", typeof(int), typeof(MyCustomControl), new UIPropertyMetadata(ValuePropertyChangedHandler));
public static void ValuePropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
((MyCustomControl)sender).Value = (int)e.NewValue;
}
}
我得到的错误如下:
System.Windows.Data Error: 40 : BindingExpression path error: 'Number' property not found on 'object' ''MyCustomControl' (Name='')'. BindingExpression:Path=Number; DataItem='MyCustomControl' (Name=''); target element is 'MyCustomControl' (Name=''); target property is 'ValueProperty' (type 'Int32')
答案 0 :(得分:0)
不确定,但我认为您必须在绑定中提供相对来源,如:
Label Content="{Binding Number, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
如果你在控件
中,请将Window
替换为UserControl