请关注我的代码:
<Grid DataContext="{Binding ElementName=dataGrid_services, Path=SelectedItem}"
Width="766">
<RadioButton Content="visit" IsChecked="{Binding Path=type_services}"
FontFamily="Tahoma"/>
我想从radiobutton绑定缺血属性,但返回值不是假或真。 值是字符串。请帮我怎么绑定这个值? 提前谢谢
答案 0 :(得分:0)
您必须定义一个值转换器,以便从字符串转换为布尔值,并将其与RadioButton
一起使用。
public class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Convert.ToBool(value);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Convert.ToString(value);
}
}
在XAML中,使用
<RadioButton Content="visit" IsChecked="{Binding Path=type_services, Converter={StaticResource stringToBoolConverter}}"
FontFamily="Tahoma"/>
其中stringToBoolConverter
在父元素的资源中定义。
<Window.Resources>
<local:StringToBoolConverter x:Key="stringToBoolConverter" />
</Window.Resources>
答案 1 :(得分:0)
使用IValueConverter。
给定此窗口包含您的单选按钮和相关绑定:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525" x:Name="dataGrid_services">
<Window.Resources>
<local:CheckedConverter x:Key="converter"/>
</Window.Resources>
<Grid DataContext="{Binding ElementName=dataGrid_services, Path=SelectedItem}" Width="766">
<RadioButton Content="visit" IsChecked="{Binding Path=type_services, Converter={StaticResource converter}}" FontFamily="Tahoma"/>
</Grid>
更改是为本地(或转换器所在的命名空间)添加命名空间引用:
xmlns:local="clr-namespace:WpfApplication1"
创建转换器资源:
<Window.Resources>
<local:CheckedConverter x:Key="converter"/>
</Window.Resources>
并使用转换器资源:
IsChecked="{Binding Path=type_services, Converter={StaticResource converter}}"
转换器看起来像这样,只需从字符串转换为布尔值。
public class CheckedConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string typeService = value as string;
if (typeService == "Yes it is")
{
return true;
}
if (typeService == "Nope")
{
return false;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool typeService = (bool)value;
if (typeService)
{
return "Yes it is";
}
else
{
return "Nope";
}
}
}