将WPF简单条件从Code Behind移动到XAML

时间:2013-01-25 17:24:47

标签: wpf mvvm

我有一个简单的条件,一个名为tbDestinationTableName的文本框,只有在从ComboBox cbConnection进行任何选择时才允许用户输入。我目前在codeBehind中执行此操作。如果可以在XAML中完成,有人可以更正以下代码吗?

<ComboBox x:Name="cbConnection"
                  ItemsSource="{Binding Source={StaticResource XmlConnectionList}, XPath=//ComboItem}"
                  DisplayMemberPath="Key"
                  SelectedValuePath="Value"
                  SelectedValue="{Binding Path=ConnectionString,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}" 
                  Margin="{StaticResource ConsistentMargins}"
                  />

<kit:WatermarkTextBox Name="tbDestinationTableName" Margin="{StaticResource ConsistentMargins}"
                  TextChanged="tbDestinationTableName_TextChanged"
                  Text="{Binding Path=DestinationTableName, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                  Watermark="Destination Table"
                  IsEnabled="{Binding Path=ValidCreate}"/>

1 个答案:

答案 0 :(得分:2)

我相信您可以使用自定义文本框执行此类操作

<kit:WatermarkTextBox>
    <kit:WatermarkTextBox.Style>
        <Style TargetType="{x:Type kit:WatermarkTextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=cbConnection, Path=SelectedIndex}" Value="-1">
                    <Setter Property="IsReadOnly" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </kit:WatermarkTextBox.Style>
</kit:WatermarkTextBox>

如果你想使用IsEnabled,那么不应该在套件中设置:WatermarkTextBox的xaml

只需使用另一个Datatrigger:

   <kit:WatermarkTextBox Name="tbDestinationTableName" Margin="{StaticResource ConsistentMargins}"                     
                TextChanged="tbDestinationTableName_TextChanged"
                Text="{Binding Path=DestinationTableName, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
              Watermark="Destination Table">
    <kit:WatermarkTextBox.Style>
        <Style TargetType="{x:Type kit:WatermarkTextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=cbConnection, Path=SelectedIndex}" Value="-1">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=ValidCreate}" Value="False">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </kit:WatermarkTextBox.Style>
</kit:WatermarkTextBox>