我有三個TEXTBOX綁定到LABEL。當我在TEXTBOX中鍵入內容時,TextBox文本值被設置爲Label。 問題是我想設置可見性的標籤,當文本框爲空,反之亦然。如何使用WPF中的可見性轉換?如何設置綁定到文本框的標籤的可見性?
在.XAML文件:
<TextBox Name="txtEmail1" Grid.Column="1" Grid.Row="0" Text="Email" HorizontalAlignment="Stretch" Margin="2" VerticalAlignment="Stretch"/>
<TextBox Name="txtEmail2" Grid.Column="1" Grid.Row="0" Text="Email2" Visibility="Collapsed" Margin="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<TextBox Name="txtEmail3" Grid.Column="1" Grid.Row="0" Text="Email3" Visibility="Collapsed" Margin="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<Label Name="lblContactEmail1" Content="{Binding Path=Text, ElementName=txtEmail1, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
<Label Name="lblContactEmail2" Content="{Binding Path=Text, ElementName=txtEmail2, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
<Label Name="lblContactEmail3" Content="{Binding Path=Text, ElementName=txtEmail3, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
我曾嘗試爲: 使用下面類StringToVisibilityConverter.cs
<UserControl xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" x:Class="XtremeProcurementWPF.UserControls.usContactForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cv="clr-namespace:MyWPF"
mc:Ignorable="d">
<UserControl.Resources>
<cv:StringToVisibilityConverter x:Key="visibilityconverter" />
</UserControl.Resources>
<Grid>
<TextBox Name="txtEmail1" Grid.Column="1" Grid.Row="0" Text="Email" HorizontalAlignment="Stretch" Margin="2" VerticalAlignment="Stretch" />
<Label Name="lblContactEmail1" Content="{Binding Path=Text, ElementName=txtEmail1, Mode=OneWay, UpdateSourceTrigger=PropertyChanged,Converter={StaticResource visibilityconverter}}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>
</UserControl>
問題:它顯示的文本標籤爲 「可見」,而不是在文本框中輸入的確切文本。
幫助讚賞! 謝謝!在你的資源
public class StringToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var s = value as string;
if (string.IsNullOrWhiteSpace(s))
return Visibility.Collapsed;
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
現在的地方您註冊轉換器:
仔細看看我的例子。你是**不是**應該使用轉換器作爲'Content'屬性,但是對於'Visibility'屬性,如我的示例所示。內容應該保留原來的樣子。 –
檢查我對我的回答所做的修改。 –