1

Здравствуйте.

Есть UserControl, в котором есть ComboBox. При изменении значения в ComboBox текст выделенного элемента должен присваиваться свойству Text ComboBoxa, но он не устанавливается. В окне Window это работает, а в UserControl - нет. Как сделать так, чтобы и в UserControl работало тоже?

public partial class ComboBoxControl : UserControl
{
    public ComboBoxControl()
    {
        InitializeComponent();

        CheckableCombo.Items.Add("Текст 1");
        CheckableCombo.Items.Add("Текст 2");
        CheckableCombo.Items.Add("Текст 3");
        CheckableCombo.Items.Add("Текст 4");
    }

    public object ItemsSource
    {
        get { return (object)GetValue(ItemsSourceProperty); }
        set
        {
            SetValue(ItemsSourceProperty, value);

            SetText();
        }
    }

    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(object), typeof(ComboBoxControl));

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(ComboBoxControl));

    public string DefaultText
    {
        get { return (string)GetValue(DefaultTextProperty); }
        set { SetValue(DefaultTextProperty, value); }
    }

    public static readonly DependencyProperty DefaultTextProperty = DependencyProperty.Register("DefaultText", typeof(string), typeof(ComboBoxControl));

    public void CheckableCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SetText();
    }

    private void SetText()
    {
        this.Text = (this.ItemsSource != null) ?
            this.ItemsSource.ToString() : this.DefaultText;

        if (string.IsNullOrEmpty(this.Text))
        {
            this.Text = CheckableCombo.Items[0].ToString();
        }
    }
}

1 ответ 1

3

.

set
{
    SetValue(ItemsSourceProperty, value);
    SetText();
}

Это некорректно. В свойстве-обёртке не должно быть иного содержимого, кроме как вызовов GetValue и SetValue. Для отслеживания изменения свойства задайте PropertyChangedCallback при его регистрации.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.