从ItemContainerStyle(WPF)访问ListView ItemSource绑定

时间:2019-03-22 16:04:41

标签: c# wpf listview user-interface

我有一个ListView控件,该控件根据用户的位置显示用户列表。 ListView的ItemSource绑定到ViewModel中的用户列表。

<UserControl
x:Class="Views.UserPositionView"
d:DataContext="{d:DesignInstance viewModels:UserPositionViewModel, IsDesignTimeCreatable=True}">
<ListView
    ItemsSource="{Binding UserPositions}">
    <ListView.ItemsPanel>
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                <!-- What to bind here? -->
                <Setter Property="IsHitTestVisible" Value="{Binding ElementName=UserButton Path=IsEnabled}"/>
            </ListView.ItemContainerStyle>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Button Name="UserButton"
                    IsEnabled="{Binding IsPresent} />
        </DataTemplate>
</ListView>

这是ViewModel类(简化)。

//ViewModel definition
public class UserPositionViewModel: ViewModelBase {
    private readonly Dictionary<int, UserViewModel> m_users =
            new Dictionary<int, UserViewModel>();

    public IEnumerable<UserViewModel> UserPositions { get { return m_users.Values; } }
}

public class UserViewModel: ViewModelBase {
    private bool m_isPresent;
    public bool IsPresent {get; set {Set(()=> IsPresent, ref m_isPresent, value);}
}

但是,我在绑定IsHitTestVisible中的ListView.ItemContainerStyle属性时遇到了麻烦。本质上,我想将其绑定到UserPositions中每个UserViewModel的IsPresent属性。我认为这是不可能的,因为ListView.ItemContainerStyle是ListView的根项。我试图将其绑定到按钮的elementname,但这也不起作用。我收到此错误:

 Cannot find source for binding with reference 'ElementName=UserButton '. BindingExpression:Path=IsEnabled; DataItem=null; target element is 'ListViewItem' (Name='');

解决此问题的最佳方法是什么?理想情况下,我想访问UserViewModel中的每个<ListView.ItemContainerStyle>

0 个答案:

没有答案