【问题标题】:WPF DataTrigger for ComboBox Item Change用于组合框项目更改的 WPF DataTrigger
【发布时间】:2017-01-14 18:57:01
【问题描述】:

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

我尝试了以下代码:

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

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

【问题讨论】:

    标签: c# wpf xaml datatrigger multidatatrigger


    【解决方案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属性在DataTemplate实例化后要改变其值,则所属类需要实现INotifyPropertyChanged接口。

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2020-07-18
      • 2011-03-19
      • 1970-01-01
      • 2019-03-07
      • 2017-12-13
      • 2016-01-19
      • 2017-11-14
      • 1970-01-01
      相关资源
      最近更新 更多