Tho*_*lin 16 c# wpf xaml binding
是否可以显示此TextBlock,仅在Address.Length > 0
?我想直接在xaml中执行此操作,我知道我可以以编程方式放置所有控件
<TextBlock Text="{Binding Path=Address}" />
Run Code Online (Sandbox Code Playgroud)
Don*_*nut 22
基本上,您需要编写一个,IValueConverter
以便您可以将您的Visibility
属性绑定TextBox
到Address
字段或您创建的新字段.
如果你绑定到Address
字段,这里的绑定可能是这样的::
<TextBlock Text="{Binding Path=Address}"
Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}}" />
Run Code Online (Sandbox Code Playgroud)
然后StringLengthVisiblityConverter
看起来像这样:
public class StringLengthVisiblityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.ToString().Length == 0)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
}
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要将转换器作为资源添加,使用这样的语法(其中src
映射到定义转换器的命名空间):
<src:StringLengthVisiblityConverter x:Key="StringLengthVisiblityConverter" />
Run Code Online (Sandbox Code Playgroud)
我会与另一个叫布尔属性做到这一点HasAddress
,它返回Address.Length > 0
.
<!-- In some resources section -->
<BooleanToVisibilityConverter x:Key="Bool2VisibilityConverter" />
<TextBlock
Text="{Binding Address}"
Visibility="{Binding HasAddress, Converter={StaticResource Bool2VisibilityConverter}}"
/>
Run Code Online (Sandbox Code Playgroud)
您还应该记得HasAddress
在setter中通知属性更改Address
.
归档时间: |
|
查看次数: |
21534 次 |
最近记录: |