将按钮的可见性绑定到两个文本框的内容的最简洁方法 [英] Cleanest way to bind a Button's visibility to the contents of two textboxes
问题描述
我的应用程序中有一个 Button
,它的启用"与 TextBox
是否为空相关联:
I have a Button
within my app whose "enabledness" I have bound to whether a TextBox
is empty as so:
<Button Content="Go"
IsEnabled="{Binding Text,
Converter={StaticResource EnableIfStringNotEmptyDataSource},
ElementName=MyTextbox}"/>
(为简洁起见省略了 EnableIfStringNotEmptyDataSource
的实现).
(implementation of EnableIfStringNotEmptyDataSource
omitted for brevity).
这会在 TextBox
的文本更改时自动更改状态.
This automatically changes the state when the TextBox
's text changes.
以相同的方式将属性绑定到两个文本框是否都是空的最优雅的方式是什么?
What would be the most elegant way of binding a property in the same manner to whether two textboxes are both empty or not?
推荐答案
对于 Silverlight 这可能是最干净的:
For silverlight this is probably the cleanest it gets:
<TextBox Text="{Binding TB1Text, Mode=TwoWay}" />
<TextBox Text="{Binding TB2Text, Mode=TwoWay}"/>
<Button Content="Lorem Ipsum" IsEnabled="{Binding ButtonIsEnabled}"/>
private string _TB1Text;
public string TB1Text
{
get { return _TB1Text; }
set
{
if (_TB1Text != value)
{
_TB1Text = value;
PropertyChanged.Notify(() => this.TB1Text);
PropertyChanged.Notify(() => this.ButtonIsEnabled);
}
}
}
private string _TB2Text;
public string TB2Text
{
get { return _TB2Text; }
set
{
if (_TB2Text != value)
{
_TB2Text = value;
PropertyChanged.Notify(() => this.TB2Text);
PropertyChanged.Notify(() => this.ButtonIsEnabled);
}
}
}
public bool ButtonIsEnabled
{
get { return !(String.IsNullOrEmpty(TB1Text) && String.IsNullOrEmpty(TB2Text)); }
}
(PropertyChanged.Notify
只是一个扩展方法,无需传递字符串即可引发事件)
(PropertyChanged.Notify
is just an extension method which raises the event without the need to pass around strings)
不会使用绑定而是使用 MultiDataTrigger
:
Would not use a binding but a MultiDataTrigger
:
<TextBox Name="tb1"/>
<TextBox Name="tb2"/>
<Button Content="Lorem Ipsum">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Text, ElementName=tb1}" Value="{x:Static sys:String.Empty}"/>
<Condition Binding="{Binding Text, ElementName=tb2}" Value="{x:Static sys:String.Empty}"/>
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="False"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
顺便说一下,您的一个 TextBox 案例不需要转换器:
By the way, you do not need a converter for your one TextBox case:
<Button Content="Lorem Ipsum" IsEnabled="{Binding Text.Length,
ElementName=MyTextBox}"/>
这篇关于将按钮的可见性绑定到两个文本框的内容的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!