Pourquoi la propriété de dépendance de mon Custom UserControl ne fonctionne-t-elle pas avec la liaison?

StackOverflow https://stackoverflow.com/questions/1808204

Question

La propriété de dépendance

de My Custom UserControl sera liée correctement si la valeur est de manière statique définie dans le code XAML l'appelant, comme suit:

ItemTypeIdCode="addresses"

mais pas si la valeur est liée dynamiquement elle-même:

ItemTypeIdCode="{Binding ItemTypeIdCode}"

Que dois-je faire à mon contrôle utilisateur personnalisé pour que sa propriété de dépendance réagisse à la valeur liée à un autre contrôle?

Voici mon code:

XAML:

<Window x:Class="TestDepenProp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:TestDepenProp.Controls"
    Title="Window1" Height="300" Width="300">
    <StackPanel 
        HorizontalAlignment="Left"
        Margin="10">
        <controls:DropDown 
            ItemTypeIdCode="{Binding ItemTypeIdCode}"  
            SelectedValue="672"
            Width="150"
            Margin="0 0 0 5"/>
        <TextBlock Text="{Binding ItemTypeIdCode}"/>
    </StackPanel>
</Window>

Code-Behind:

using System.Windows;
using System.ComponentModel;

namespace TestDepenProp
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        #region ViewModelProperty: ItemTypeIdCode
        private string _itemTypeIdCode;
        public string ItemTypeIdCode
        {
            get
            {
                return _itemTypeIdCode;
            }

            set
            {
                _itemTypeIdCode = value;
                OnPropertyChanged("ItemTypeIdCode");
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            ItemTypeIdCode = "addresses";
        }
        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}

DropDown.xaml:

<UserControl x:Class="TestDepenProp.Controls.DropDown"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <ComboBox SelectedValuePath="Key"
                  DisplayMemberPath="Value"
                  SelectedValue="{Binding SelectedValue}"
                  Margin="0 0 0 10"
                  ItemsSource="{Binding DropDownValues}" />
    </StackPanel>
</UserControl>

DropDown.xaml.cs:

using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace TestDepenProp.Controls
{
    public partial class DropDown : UserControl, INotifyPropertyChanged
    {

        public static readonly DependencyProperty ItemTypeIdCodeProperty = DependencyProperty.Register("ItemTypeIdCode", typeof(string), typeof(DropDown));

        public string ItemTypeIdCode
        {
            get { return (string)GetValue(ItemTypeIdCodeProperty); }
            set { SetValue(ItemTypeIdCodeProperty, value); }
        }

        #region ViewModelProperty: DropDownValues
        private ObservableCollection<KeyValuePair<string, string>> _dropDownValues = new ObservableCollection<KeyValuePair<string, string>>();
        public ObservableCollection<KeyValuePair<string, string>> DropDownValues
        {
            get
            {
                return _dropDownValues;
            }

            set
            {
                _dropDownValues = value;
                OnPropertyChanged("DropDownValues");
            }
        }
        #endregion

        #region ViewModelProperty: SelectedValue
        private string _selectedValue;
        public string SelectedValue
        {
            get
            {
                return _selectedValue;
            }

            set
            {
                _selectedValue = value;
                OnPropertyChanged("SelectedValue");
            }
        }
        #endregion

        public DropDown()
        {
            InitializeComponent();
            DataContext = this;

            Loaded += new RoutedEventHandler(DropDown_Loaded);
        }

        void DropDown_Loaded(object sender, RoutedEventArgs e)
        {
            GetDropDownValues();
        }

        void GetDropDownValues()
        {
            switch (ItemTypeIdCode)
            {
                case "addresses":
                    DropDownValues.Add(new KeyValuePair<string, string>("111", "762 Main St."));
                    DropDownValues.Add(new KeyValuePair<string, string>("222", "7384 First Ave."));
                    DropDownValues.Add(new KeyValuePair<string, string>("333", "8728 Second St."));
                    break;
                case "customers":
                    DropDownValues.Add(new KeyValuePair<string, string>("672", "Jim Smith"));
                    DropDownValues.Add(new KeyValuePair<string, string>("281", "James Anders"));
                    DropDownValues.Add(new KeyValuePair<string, string>("321", "Angie Wonderson"));
                    DropDownValues.Add(new KeyValuePair<string, string>("221", "Hal Cloud"));
                    DropDownValues.Add(new KeyValuePair<string, string>("123", "Hugh Brandley"));
                    break;
                default:
                    break;
            }
        }


        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion


    }
}
Était-ce utile?

La solution

Je pense que vous devez ajouter PropertyChangedCallback à votre propriété de dépendance ItemTypeIdCodeProperty. Dans ce rappel, vous devez appeler GetDropDownValues ??().

Autres conseils

Je suppose que la liste déroulante ne contient aucune entrée. C'est en effet un peu délicat. Un contrôle fonctionne dans 2 "espaces d'adressage" totalement indépendants. La première est ses propres données, comme toutes les propriétés de dépendance. Le deuxième "espace adresse" est le contexte de données qu'il hérite de son parent. Si rien de spécial n'est fait, toutes les liaisons fonctionnent sur le contexte de données. Si vous souhaitez faire référence aux données du contrôle, vous devez ajouter une "référence" explicite. à vous-même:

<UserControl x:Class="TestDepenProp.Controls.DropDown"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="self">
<StackPanel>
    <ComboBox SelectedValuePath="Key"
              DisplayMemberPath="Value"
              SelectedValue="{Binding SelectedValue, ElementName=self}"
              Margin="0 0 0 10"
              ItemsSource="{Binding DropDownValues, ElementName=self}" />
</StackPanel>

OnPropertyChanged n'est pas nécessaire, cela est déjà géré par la logique de propriété de dépendance.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top