2016-09-07 112 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接口。