开发者

Datatrigger on textbox not working

Hi i am trying to write a datatrigger in which i have to clear a textbox content on checkbox checked.My Code is given below

It works as long as you dont type anything in the textbox.As soon as i type in the textbox the datatrigger fails to work.How can i solve this

<Window x:Class="CheckboxTextbox.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style x:Key="cbStyle" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=Chk,Path=IsChecked}" Value="True">
                    <Setter Property="Text" Value="{x:Null}"/>
                开发者_如何学Python</DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <CheckBox Name="Chk" Content="test"/>
        <TextBox Style="{StaticResource cbStyle}">

        </TextBox>
    </StackPanel>
</Window>


Unlike an animation which can "hold" a dependency property at a specified value once the animation ends, a DataTrigger sets the target property and then is done until the source property changes.

In other words, in your example if you put some text in the text box, then check the box, the text will be cleared. But then if you start typing in the text box again, DataTrigger isn't going to do anything until the check box changes again. That's why when you uncheck and re-check the box, the text is cleared again.

So what you may want to do is in your DataTrigger, set the text box's IsReadOnly property to true. This will prevent you from typing in the box while the DataTrigger is active.

<DataTrigger Binding="{Binding ElementName=Chk,Path=IsChecked}" Value="True">
    <Setter Property="Text" Value="{x:Null}"/>
    <Setter Property="IsReadOnly" Value="True"/>
</DataTrigger>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜