开发者

Change a Button IsEnabled state through DataTrigger

I'm trying to change the IsEnabled state of a button based on a TextBox.TextChanged event or a ComboBox.SelectionChanged event. I was trying to do this with events but the enabled state was being changed by the data being loaded. I'm populating a WPF UIElement Grid with Text Boxes and Combo Boxes. The grid is being populated via ItemSource of a List.

What I'm looking for is the editor containing the grid to be populated with data and the Apply buttons enabled state to be set to false until the user changes the data of a text box or combo box. At that time the DataTrigger should fire and change the btnApply.IsEnabled to true. I wasn't sure what to put for the Value of the events but "True" just didn't seem to be correct and True and HasChanged didn't work.

I'm open to different approaches other than a DataTrigger provided the IsEnabled is false be default when the control is presented to the user.

Here is what I have so far:

  <UserControl.Resources>
    <Style x:Key="tbChanged"开发者_运维问答 TargetType="{x:Type Button}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=TextBox.TextChanged}" Value="HasChanged">
          <Setter Property="Button.IsEnabled" Value="True"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=ComboBox.SelectionChanged}" Value="HasChanged">
          <Setter Property="Button.IsEnabled" Value="True"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </UserControl.Resources>

  <Button x:Name="btnApply" Content="Apply" Height="22" Width="50" Margin="5,5,0,0"  HorizontalAlignment="Left" VerticalAlignment="Top" IsEnabled="False" Click="btnApply_Click" Style="{StaticResource tbChanged}"/> 


These triggers are not suitable for this, they are either active or inactive, meaning that they have a timeline while events do not. You could use Interactivity from the Blend SDK though, which has an EventTrigger which can call a ChangePropertyAction, e.g.

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
<TextBox Name="myTextBox" />
<ComboBox Name="myComboBox" />
<Button IsEnabled="False" Content="Test">
    <i:Interaction.Triggers>
        <i:EventTrigger SourceName="myTextBox" EventName="TextChanged">
            <ei:ChangePropertyAction PropertyName="IsEnabled" Value="True"/>
        </i:EventTrigger>
        <i:EventTrigger SourceName="myComboBox" EventName="SelectionChanged">
            <ei:ChangePropertyAction PropertyName="IsEnabled" Value="True"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

There are also native EventTriggers but they are very restricted and you will probably not be able to get this done using them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜