0

我有以下数据模板:

 <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 开始。

我还能做些什么呢?

4

1 回答 1

0

我犯了一个错误并覆盖了我的自定义控件的DataContextValue ,因此它无法在其上下文中找到该属性。

所以,我删除了以下行:

 DataContext = this;

现在它按预期工作。

于 2016-09-29T11:33:32.253 回答