C# 绑定到DependencyProperty WPF时出现BindingExpression错误
当我试图从样式中将int值绑定到自定义控件中的DependencyProperty时,出现了一个问题 MyClassVM包含一个名为int的数字。当我以同样的方式绑定时,它会完美地显示在标签中,但不会设置在自定义控件上。例如,如果我从“{Binding Number}”改为“15”,那么在自定义控件上,一切都很好C# 绑定到DependencyProperty WPF时出现BindingExpression错误,c#,wpf,binding,dependency-properties,C#,Wpf,Binding,Dependency Properties,当我试图从样式中将int值绑定到自定义控件中的DependencyProperty时,出现了一个问题 MyClassVM包含一个名为int的数字。当我以同样的方式绑定时,它会完美地显示在标签中,但不会设置在自定义控件上。例如,如果我从“{Binding Number}”改为“15”,那么在自定义控件上,一切都很好 <Style TargetType="{x:Type ItemsControl}" x:Key="TestKey"> <Setter Property="Te
<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>
我得到的错误如下所示:
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')
不确定,但我认为您必须在绑定中提供一个相对源,如:
Label Content="{Binding Number, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
将
窗口
替换为用户控件
如果您在控件中标签起作用,只有自定义控件不起作用。。。我在我的ClassVM中得到了变量。。。但这不起作用……”ctrl:MyCustomControl.ValueProperty=“{Binding HoursresRemining,RelativeSource={RelativeSource FindAncestor,AncestorType=local:MyClassVM}}”
Label Content="{Binding Number, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"