【问题标题】:Binding a ListView selected item to a user control将 ListView 选定项绑定到用户控件
【发布时间】:2013-12-23 21:48:09
【问题描述】:

我有一个包含用户列表视图的页面:

<ListView ItemsSource="{Binding UserList}"
          SelectedItem="{Binding SelectedUser}">
    <GridView>
        <GridViewColumn DisplayMemberBinding="{Binding Id}" />
        <GridViewColumn DisplayMemberBinding="{Binding Name}"/>
    </GridVie>
</ListView>

我还有一个用户控件,它将显示该 ListView 中选定用户的所有数据。所以我将SelectedUser绑定到UserUc的依赖属性CurrentUser

<userControls:UserUc CurrentUser="{Binding SelectedUser}" />

用户控件不显示数据!为什么?

Edit

我将此添加到页面后面的代码中:

public static readonly DependencyProperty SelectedUserProperty = WpfDpHelper.Register<UserListUc, User>(i => i.SelectedUser, Callback);

private static void Callback(UserListUc userListUc, DependencyPropertyChangedEventArgs<User> DependencyPropertyChangedEventArgs)
{
    Debug.WriteLine("user selection changed");
}

当我更改任何用户的选择时,setter 会被解雇

Second edit:用户控制

<UserControl ...
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <ListView ItemsSource="{Binding CurrentUser.CommentList}">
        <!-- I want to show the user comments -->
    </ListView>
</UserControl>

Code behind

public static readonly DependencyProperty CurrentUserProperty = WpfDpHelper.Register<UserUc, User>(i => i.CurrentUser);
public User CurrentUser
{
    get { return (User) GetValue(CurrentUserProperty); }
    set { SetValue(CurrentUserProperty, value); }
}

【问题讨论】:

  • 您是否在 VS 输出窗口中查看了一些绑定异常?
  • 是的,完全没有错误
  • 您确定DataContext 设置正确吗?
  • SelectedUser 的 setter 是否触发 PropertyChanged?您能否发布与相关依赖属性相关的 UserUc 代码隐藏部分?
  • SelectedUser 是否由 ListView 设置?我认为您需要双向绑定

标签: c# wpf listview data-binding dependency-properties


【解决方案1】:

如果您将用户控件中的 datacontext 设置为 self - 那是错误的。 请使用 ElementName 绑定。所以你所要做的就是删除你的 DataContext="{Binding RelativeSource={RelativeSource Self}}"

 <UserControl x:Name="uc">
   <ListView ItemsSource="{Binding ElementName=uc,CurrentUser.CommentList}">
    <!-- I want to show the user comments -->
   </ListView>

【讨论】:

  • 您说得对,先生。我不得不删除用户控件中的 DataContrext。但我不明白为什么我不能在他们两个中都使用 DataContext ?
  • 检查 H.B. 的 cmets。这里:stackoverflow.com/questions/11226843/…这是一个很好的解释:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多