【问题标题】:How do I bind a custom UserControl to the current item inside a ItemTemplate?如何将自定义 UserControl 绑定到 ItemTemplate 中的当前项?
【发布时间】:2011-11-28 17:57:04
【问题描述】:

我有一个ListBox,它的数据绑定到ObservableCollection
DataTemplate 中,我有这个想要绑定到当前项目的自定义用户控件。 我怎么做? 绑定路径应该是什么?

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

【问题讨论】:

    标签: c# data-binding silverlight-4.0 user-controls itemtemplate


    【解决方案1】:

    MyControl.DataContext 属性在这种情况下已经绑定到您的项目视图模型。

    【讨论】:

      【解决方案2】:

      您的 MyItem 是数据上下文 - 如果您想绑定到 My Item 的某个成员,那么它的:

      Binding Path=my_item_member 
      

      我想你想要完全绑定到 MyItem:

      Binding Path=.
      

      您的控件可能还需要一个 DataTemplate(除了 ListBoxItems 之外),它将 MyItems 成员映射到您的控件字段。

      【讨论】:

        猜你喜欢
        • 2013-10-09
        • 1970-01-01
        • 1970-01-01
        • 2013-01-20
        • 1970-01-01
        • 2012-02-09
        • 1970-01-01
        • 2012-07-10
        • 2011-03-17
        相关资源
        最近更新 更多