2016-09-29 68 views
0
工作

我有以下的DataTemplate:自定义依赖属性不UWP模板与TemplatedParent

<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; 
    } 
    } 

TextBlockComboBox结合工作好所以DataContext是正确的。

我了解到模板中的自定义绑定仅在RelativeSource设置为TemplatedParent时才起作用。

不幸的是我的自定义控件的ActualValue属性始终设置为缺省值(这显然是错误的),当我改变数值,它总是从0

我能做的还有什么关于这个开始?

回答

0

我犯了一个错误,改写我的自定义控件的的DataContext所以它无法找到它的上下文中的Value财产。

所以,我删除了以下行:

DataContext = this; 

现在按预期工作。