开发者

How do I bind a custom UserControl to the current item inside a ItemTemplate?

I have a ListBox that is data bound to an ObservableCollection.

Inside the DataTemplate, I have this custom user control that I want to bind to the current item. How do I do that? What should the binding path be?

Model:

private ObservableCollection<MyItem> _items;
public ObservableCollection<MyItem> Items
{
  get { return _items; }
  set
  {
    if (_items.Equals(value))
      return;
    _items = value;
    RaisePropertyChanged("Items");
  }
}

XAML:

<ListBox ItemsSource="{Binding Items}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock TextWrapping="Wrap" Text="{Binding Id}" Margin="2"/>
        <TextBlock TextWrapping="Wrap" Text="{Binding Name}" Margin="2"/>
        <uc:MyControl MyValue="{Binding <WHATSHOULDTHISBE>, Mode=TwoWay}" Margin="2"/>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>

User control:

public partial class MyControl : UserControl
{
  public MyItem MyValue
  {
    get { return (MyItem)GetValue(MyProperty); }
    set { SetValue(MyProperty, value); }
  }

  public static readonly DependencyProperty MyProperty = DependencyProperty.Register("MyValue",
                                                        typeof(MyItem), typeof(MyControl),
                                                        new PropertyMetadata(
                                                   开发者_开发技巧       new PropertyChangedCallback(PropertyChanged)));
  public MyControl()
  {
    InitializeComponent();
  }

  private static void PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  {
    MyControl c = obj as MyControl;
    if (c != null)
    {
      // TODO: do something here 
    }
  }
}


MyControl.DataContext property would already be bound to your item view model in this case.


Your MyItem is the data context - if you want to bind to some member of My Item then its:

Binding Path=my_item_member 

To bind to MyItem in its entirety I think you want:

Binding Path=.

Your might also need a DataTemplate for your control (in addition to the you have for the ListBoxItems) that maps the MyItems members to your control fields.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜