2016-09-07 122 views
-1

我在XAMLWPF DataTrigger的组合框项目更改

<DataTemplate> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="Auto"/> 
      <ColumnDefinition/> 
     </Grid.ColumnDefinitions> 
     <ComboBox Grid.Column="0" SelectedItem="{Binding Type, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"> 
      <ComboBoxItem Content="1">Mobile</ComboBoxItem> 
      <ComboBoxItem Content="2">Phone</ComboBoxItem> 
     </ComboBox> 
     <TextBox Text="{Binding Contact, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> 
    </Grid> 
</DataTemplate> 

设计了一个联系中的属性是

public int Type { get; set; } 
public string Contact { get; set; } 

Type is ZERO初始值(即Type = 0;)。

条件以实现:

  1. 如果数据类型为等于1或2,然后我需要启用文本框 - IsEnabled = True
  2. 如果数据类型为1,则TextBox.MaxLength应为10
  3. 如果类型是2,则TextBox.MaxLength应该是11

我尝试以下一块代码的:

<DataTemplate.Triggers> 
    <DataTrigger Binding="{Binding Path=Type}" Value="0"> 
     <Setter Property="TextBox.IsEnabled" Value="False" /> 
    </DataTrigger> 

    <DataTrigger Binding="{Binding Path=Type}" Value="1"> 
     <Setter Property="TextBox.MaxLength" Value="10" /> 
    </DataTrigger> 

    <DataTrigger Binding="{Binding Path=Type}" Value="2"> 
     <Setter Property="TextBox.MaxLength" Value="11" /> 
    </DataTrigger> 
</DataTemplate.Triggers> 

但上述代码不起作用。请帮助我如何实现DataTemplateDataTrigger中的逻辑。

回答

1

你的文本框可以有一个风格与DataTriggers:

<TextBox Text="{Binding Contact, UpdateSourceTrigger=PropertyChanged}"> 
    <TextBox.Style> 
     <Style TargetType="TextBox"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Type}" Value="0"> 
        <Setter Property="IsEnabled" Value="False" /> 
       </DataTrigger> 
       <DataTrigger Binding="{Binding Type}" Value="1"> 
        <Setter Property="MaxLength" Value="10" /> 
       </DataTrigger> 
       <DataTrigger Binding="{Binding Type}" Value="2"> 
        <Setter Property="MaxLength" Value="11" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBox.Style> 
</TextBox> 

如果Type属性suposed的DataTemplate中实例化后改变其值,所属的类必须实现INotifyPropertyChanged接口。