Не работает свойство SelectedItem для пользовательского элемента управления
Имеется пользовательский элемент управления UCComboBox который является "оберткой" для обычного выпадающего списка (кобмобокса). Код:
<DockPanel>
<TextBlock Text="{Binding LabelText, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}" Margin="5"/>
<ComboBox
Margin="5"
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}"
SelectedItem="{Binding SelectedParticipant.CaseStatusType}"
/>
<!--SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}"-->
</DockPanel>
Когда я явно определяю свойство SelectedItem для комбобокса, как в вышеприведенном примере, то элемент управления работает нормально. Когда же я пытаюсь сделать его переопределяемым через свойство зависимостей, привязка к выбранному элементу перестает работать, хотя ошибки привязки XAML отсутствуют. Код:
<DockPanel>
<TextBlock Text="{Binding LabelText, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}" Margin="5"/>
<ComboBox
Margin="5"
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}"
SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}"
/>
</DockPanel>
Свойства зависимостей:
public partial class UCComboBox : UserControl
{
public UCComboBox()
{
InitializeComponent();
}
public string LabelText
{
get { return (string)GetValue(LabelTextProperty); }
set { SetValue(LabelTextProperty, value); }
}
// Using a DependencyProperty as the backing store for LabelText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LabelTextProperty =
DependencyProperty.Register("LabelText", typeof(string), typeof(UCComboBox), new PropertyMetadata(string.Empty));
public object ItemsSource
{
get { return (object)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemsSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(object), typeof(UCComboBox), new PropertyMetadata(null));
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedItem. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(UCComboBox), new PropertyMetadata(null));
}
Пример использования в стороннем коде:
<local:UCComboBox
LabelText="Процессуальный статус: "
ItemsSource="{Binding CaseStatusList}"
SelectedItem="{Binding SelectedParticipant.CaseStatusType}"
IsEnabled="{Binding IsEditEnabled}"
/>
Как я должен исправить свойство SelectedItem во втором примере, чтобы свойство было привязано успешно?
UPD: Я думал, что причина возможно в том, что собственное свойство выпадающего списка SelectedItem названо так же как и свойство зависимости на которое оно ссылается т.е.: SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCComboBox}}" Но после того, как я добавил "1" в название свойства зависимости и обновил само свойство зависимости и привязку, ничего не изменилось.
Ответы (1 шт):
Как оказалось, проблема была в том, что привязка не была двусторонней по умолчанию. Для того,чтобы привязка стала двусторонней в свойство зависимости нужно было передать специальный объект FrameworkPropertyMetadata c указанием на двустороннюю привязку следующим образом:
public static readonly DependencyProperty SelectedItem1Property =
DependencyProperty.Register("SelectedItem1", typeof(object), typeof(UCComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));