MVVM WPF列表框鼠标左击事件触发

本文关键字:事件 左击 鼠标 WPF 列表 MVVM | 更新日期: 2023-09-27 18:05:28

我正在用MVVM架构构建一个WPF应用程序。在一个表单中,我有2个列表框,我想执行基于过滤器的搜索。我使用的是一个普通的搜索文本框,所以我必须根据选择的列表框来区分搜索。下面是我的示例列表框:

<HeaderedContentControl Header="Visible Objects:" Height="120" Width="250" Margin="20,20,20,0">
    <ListBox Name="lstObjects" Height="100" Margin="5" ItemsSource="{Binding ProfileObjTypeToBind, Mode=OneWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Name="chkbxVisibleObjects" Grid.Column="1"
                          Content="{Binding Path=Value}" IsChecked="{Binding Path=flag,Mode=TwoWay}">
                </CheckBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</HeaderedContentControl>
<HeaderedContentControl Header="User Groups to View:" Height="120" Width="250" Margin="20,10,20,10">
    <ListBox Name="lstGroups" Height="100" Margin="5" ItemsSource="{Binding ProfileUserGrpToBind, Mode=OneWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Name="chkAllowedGroups" Content="{Binding Path=GroupName}" 
                              IsChecked="{Binding Path=flag,Mode=TwoWay}">
                </CheckBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</HeaderedContentControl>

我要做的就是识别选中的列表框,并根据文本框中输入的文本执行过滤。请帮帮我

MVVM WPF列表框鼠标左击事件触发

你不能有一个选定的列表框和能够写东西到一个文本框。你可以通过使用SelectionChanged或其他方法将引用保存到最后一个ListBox

private ListBox SelectedListBox = null;
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    SelectedListBox = (sender as ListBox); 
}

一旦你有一个引用到你最后选择的ListBox,你可以添加TextChanged事件到你的TextBox:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (SelectedListBox == null)
        return;
    string searchText = (sender as TextBox).Text;
    SelectedListBox.Items.Filter = (i) => { return ((string)i).Contains(searchText); };  // Or any other condition required
}