用于ComboBox项目更改的WPF DataTrigger

时间:2016-09-07 07:35:33

标签: c# wpf xaml datatrigger multidatatrigger

我在XAML中设计了一个联系人盒

<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. 如果Type等于1或2,那么我需要启用TextBox - IsEnabled = True
  2. 如果Type为1,则TextBox.MaxLength应为10
  3. 如果Type为2,则TextBox.MaxLength应为11
  4. 我尝试了以下代码:

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

    但上面的代码不起作用。请帮助我如何在DataTrigger内的DataTemplate中实现逻辑。

1 个答案:

答案 0 :(得分:1)

你的TextBox可以有一个带有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>

如果在实例化DataTemplate之后调用Type属性来更改其值,则拥有类需要实现INotifyPropertyChanged接口。