我正在創建一個簡單的UserControl,其中包含一組RadioButtons,然後將單個DependencyProperty設置爲一個char值(每個RadioButton都有一個與其相關的唯一char值)。我從這篇文章http://wpftutorial.net/RadioButton.html中看出我似乎是一個優雅的解決方案,但我無法實現它的效果。檢查其中一個RadioButton並不會更改該屬性。 ValueConverter的方法都不會被調用。在運行時沒有編譯時錯誤或綁定錯誤。我錯過了什麼?通過綁定設置WPF DependencyProperty的RadioButton控件集合
這是我的XAML:
<UserControl x:Class="TestClientWpf.OrderTypePicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:TestClientWpf="clr-namespace:TestClientWpf">
<WrapPanel>
<WrapPanel.Resources>
<TestClientWpf:CharMatchToBooleanConverter x:Key="converter" />
</WrapPanel.Resources>
<RadioButton IsChecked="{Binding Path=OrderType, Mode=TwoWay, Converter={StaticResource converter}, ConverterParameter=1}">Type 1</RadioButton>
<RadioButton IsChecked="{Binding Path=OrderType, Mode=TwoWay, Converter={StaticResource converter}, ConverterParameter=2}">Type 2</RadioButton>
<RadioButton IsChecked="{Binding Path=OrderType, Mode=TwoWay, Converter={StaticResource converter}, ConverterParameter=3}">Type 3</RadioButton>
</WrapPanel>
</UserControl>
我後面的代碼:
public partial class OrderTypePicker
{
public static readonly DependencyProperty OrderTypeProperty = DependencyProperty.Register("OrderType", typeof(char), typeof(OrderTypePicker), new FrameworkPropertyMetadata('1'));
public char OrderType
{
get { return (char)GetValue(OrderTypeProperty); }
set { SetValue(OrderTypeProperty, value); }
}
public OrderTypePicker()
{
InitializeComponent();
}
}
我ValueConverter:
public class CharMatchToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false;
string checkValue = value.ToString();
string targetValue = parameter.ToString();
return checkValue.Equals(targetValue, StringComparison.InvariantCultureIgnoreCase);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null;
bool useValue = (bool)value;
string targetValue = parameter.ToString();
return useValue ? char.Parse(targetValue) : (char?) null;
}
剛剛嘗試過,仍然不起作用:同樣的事情發生,代碼編譯,但屬性不會響應檢查RadioButton而改變。 – Josh
對不起,綁定到RadioButton,已經改變了我的答案,以找到控制 – GazTheDestroyer