[英]Text of Text Box Based on ComboBox Item in WPF
我在应用程序中使用一个组合框,其中的组合框项目为“是”和“否”。如果要选择组合框项目,则要将文本框的文本分配为“已清除”,如果选择了组合框项目“否”,则将其文本框分配为“未清除”。我在WPF上这样做
创建IValueConverter的实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace XAMLConverter
{
public class ComboBoxConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
if (value.ToString() == "Yes")
return "Cleared";
else if (value.ToString() == "No")
return "Not Cleared";
else
return "";
}
catch
{
return "";
}
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
将您的名称空间添加到XAML中,用于:
xmlns:conv="clr-namespace:XAMLConverter"
为转换器添加资源:
<Window.Resources>
<conv:ComboBoxConverter x:Key="ComboBoxConverter" />
</Window.Resources>
然后添加您的控件:
<StackPanel>
<ComboBox Name="SelectControl">
<ComboBoxItem Content="Yes" />
<ComboBoxItem Content="No" />
</ComboBox>
<TextBox Text="{Binding ElementName=SelectControl,
Path=SelectedItem.Content,
Converter={StaticResource ComboBoxConverter}}"
/>
</StackPanel>
触发解决方案在这里:
<ComboBox Name="cb">
<ComboBoxItem>Yes</ComboBoxItem>
<ComboBoxItem>No</ComboBoxItem>
</ComboBox>
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedItem.Content}" Value="Yes">
<Setter Property="Text" Value="cleared"/>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedItem.Content}" Value="No">
<Setter Property="Text" Value="not cleared"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.