Набор элементов управления RadioButton, устанавливающих WPF DependencyProperty через Binding - PullRequest
1 голос
/ 24 января 2012

Я пытаюсь создать простой UserControl, который содержит набор RadioButton, а затем устанавливает один DependencyProperty в значение char (каждый RadioButton имеет уникальное значение char, связанное с ним). Я беру свою реплику из этой статьи http://wpftutorial.net/RadioButton.html, которая казалась элегантным решением, но я не могу заставить его работать. Проверка одной из кнопок RadioButton не приводит к изменению свойства. Ни один из методов ValueConverter никогда не вызывается. Нет ошибок времени компиляции или связывания во время выполнения. Чего мне не хватает?

Вот мой 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();
    }
}

My 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;
    }

Ответы [ 3 ]

1 голос
/ 24 января 2012

В UserControl ваш DataContext по-прежнему указывает на обычный DataContext его родителя.

Вам необходимо привязать свойства к самому элементу управления, поэтому:

<RadioButton IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=OrderType, Mode=TwoWay, Converter={StaticResource converter}, ConverterParameter=1}">Type 1</RadioButton>
0 голосов
/ 19 июля 2012

Перейдите по этой ссылке, если вам нужно объяснение Учебник WPF

Или вы можете использовать

  `Radio1.GroupName = Radio2.GroupName = this.GetHashCode().ToString() + Radio1.GroupName;`
0 голосов
/ 24 января 2012

Для справки, мой коллега также предоставил альтернативное решение: установить свойство DataContext для экземпляра UserControl (например, в конструкторе):

    public OrderTypePicker()
    {
        InitializeComponent();
        DataContext = this;
    }
...