我有以下数据模板:
<DataTemplate x:Key="ListViewItemTemplate">
<Grid x:Name="grid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Margin="5"
Foreground="Black"
Text="{Binding ActualText}"
TextWrapping="WrapWholeWords" />
<my:CustomSelector Grid.Column="1"
ActualValue="{Binding Value, Mode=TwoWay,
RelativeSource={RelativeSource TemplatedParent}}" />
<ComboBox x:Name="cbox"
Grid.Column="2"
Width="90"
Margin="3"
VerticalAlignment="Center"
ItemsSource="{StaticResource data}"
SelectedIndex="{Binding Value,
Mode=TwoWay}" />
</Grid>
</DataTemplate>
这是它的代码隐藏文件:
public sealed partial class CustomSelector : StackPanel
{
public int ActualValue
{
get { return (int)GetValue(ActualValueProperty); }
set { SetValue(ActualValueProperty, value); }
}
// Using a DependencyProperty as the backing store for ActualValue. This enables animation, styling, binding, etc...
public static readonly DependencyPropertyActualValueProperty =
DependencyProperty.Register("ActualValue", typeof(int), typeof(CustomSelector), new PropertyMetadata(0, (x, y) =>
{
CustomSelector cc = x as CustomSelector;
int content = (int)y.NewValue;
cc.ActualValue = content;
}));
public CustomSelector()
{
this.InitializeComponent();
DataContext = this;
}
}
TextBlock
和中的绑定ComboBox
可以正常工作,因此 DataContext 是正确的。
我了解到模板中的自定义绑定只有在RelativeSource
设置为TemplatedParent
.
不幸的是,我的自定义控件的ActualValue
属性总是设置为默认值(这显然是错误的),当我更改值时,它总是从 0 开始。
我还能做些什么呢?