gpt4 book ai didi

c# - 从代码中突出显示 ListView 项 - WPF 数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:25:16 25 4
gpt4 key购买 nike

我访问过的以前的来源(但没有找到答案):

  • Highlight Row In WPF
  • Selected Item Color
  • Highlighting Items In WPF ListView
  • Triggers For Styling
  • Styles For Styling

  • 更密切相关但过于复杂/不完全是我需要的来源。

    一般信息:

    如标记,此代码位于 c# , 使用 WPF , 带有目标框架 .NET Framework 4.5 .

    笔记:
    这是我第一次尝试实现 MVVM , 所以 评论 关于我缺少的最佳实践将不胜感激(尽管这是 不是 这个问题的主要主题)。

    问题:

    带有 ListView 的 WPF和 Button . ButtonListView 中删除项目.

    ListView<String> (View) ---> RemoveStringFromList() (ViewModel)



    以上工作。我的问题是 突出显示 .

    我希望能够从 ListView 中删除一个字符串,并且在删除后 突出显示不同的项目 .

    我最初的想法是通过使用与 SelectedItemProperty 绑定(bind)的属性 ( ListView )的 SelectedItem属性 - 突出显示为 自动 .

    但在实践中, SelectedItem属性绑定(bind)有效 - 因为我可以一直按 Button并删除成为 SelectedItem 的项目根据 SelectedItemProperty 中实现的逻辑setter - 但尽管它们是按代码选择的, 它们没有突出显示。

    代码:

    MainWindow.xaml
    <Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="213.06">
    <Grid>
    <ListView ItemsSource="{Binding ItemsProperty}" SelectedItem="{Binding SelectedItemProperty}" HorizontalAlignment="Left" Height="214" Margin="35,74,0,0" VerticalAlignment="Top" Width="142">
    <ListView.View>
    <GridView>
    <GridViewColumn/>
    </GridView>
    </ListView.View>
    </ListView>
    <Button Command="{Binding RemoveString}" Content="Remove From List!" HorizontalAlignment="Left" Margin="35,10,0,0" VerticalAlignment="Top" Width="142" Height="46"/>

    </Grid>
    </Window>

    MainWindow.xaml.cs
    using System.Windows;

    namespace WpfApplication1
    {
    public partial class MainWindow : Window
    {
    private readonly MainWindowViewModel _viewModel;

    public MainWindow()
    {
    InitializeComponent();
    _viewModel = new MainWindowViewModel();
    DataContext = _viewModel;
    Show();
    }
    }
    }

    MainWindowViewModel.cs
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows.Input;

    namespace WpfApplication1
    {
    public class MainWindowViewModel : INotifyPropertyChanged
    {
    private ObservableCollection<String> _list;
    private String _selectedItem;

    public MainWindowViewModel()
    {
    _list = new ObservableCollection<String> {"1", "2", "3", "4"};
    RemoveString = new RemoveStringCommand(this);
    }

    public ObservableCollection<String> ItemsProperty
    {
    get { return _list; }
    }

    public String SelectedItemProperty
    {
    get { return _selectedItem; }
    set
    {
    if (value != null)
    {
    _selectedItem = value;
    }
    else
    {
    if (_list.Count > 0)
    {
    _selectedItem = _list[0];
    }
    }
    }
    }

    public ICommand RemoveString
    {
    get;
    private set;
    }

    public bool CanRemoveString
    {
    get { return _list.Count > 0; }
    }

    public void RemoveStringFromList()
    {
    if (SelectedItemProperty != null)
    {
    _list.Remove(SelectedItemProperty);
    }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(String propertyName)
    {
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }


    }
    }

    RemoveStringCommand.cs
    using System.Windows.Input;
    using WpfApplication1;

    namespace WpfApplication1
    {
    class RemoveStringCommand : ICommand
    {
    private MainWindowViewModel _viewModel;

    public RemoveStringCommand(MainWindowViewModel viewModel)
    {
    _viewModel = viewModel;
    }

    public event System.EventHandler CanExecuteChanged
    {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
    return _viewModel.CanRemoveString;
    }

    public void Execute(object parameter)
    {
    _viewModel.RemoveStringFromList();
    }
    }
    }

    应用图片 - 首次点击前

    enter image description here

    应用程序图片 - 单击 1 次后(注意 - 无突出显示!)

    enter image description here

    应用程序图像 - 单击 2 次后(仍然没有突出显示...)

    enter image description here

    最佳答案

    首先删除一个错误

    public MainWindow()
    {
    InitializeComponent();
    _viewModel = new MainWindowViewModel();
    DataContext = _viewModel;
    // Show(); remove this, it's not needed
    }

    我用两个可重用的辅助类做了一个例子。

    1) 第一个公共(public)类实现 INotifyPropertyChanged .在每个 ViewModel 类中重复 INPC 实现可能会有所帮助。

    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    [CallerMemberName]这里允许不包括属性名称到每个 OnPropertyChanged()称呼。编译器会自动完成。

    2) 便于命令使用的类。 (抢到 here)

    public class RelayCommand : ICommand
    {
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public event EventHandler CanExecuteChanged
    {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
    }

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
    _execute = execute;
    _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
    public void Execute(object parameter) => _execute(parameter);
    }

    3)在以下示例中,我根据您的要求更改了属性名称。不要命名属性,例如 SomethingProperty为避免与依赖属性冲突,此命名模式仅对 DP 有用。

    标记:

    <Grid>
    <ListView ItemsSource="{Binding ItemsList}" SelectedIndex="{Binding SelectedItemIndex}" HorizontalAlignment="Left" Height="214" Margin="35,74,0,0" VerticalAlignment="Top" Width="142">
    <ListView.View>
    <GridView>
    <GridViewColumn/>
    </GridView>
    </ListView.View>
    </ListView>
    <Button Command="{Binding RemoveItem}" Content="Remove From List!" HorizontalAlignment="Left" Margin="35,10,0,0" VerticalAlignment="Top" Width="142" Height="46"/>
    </Grid>

    4) View 模型:

    public class MainWindowViewModel : NotifyPropertyChanged
    {
    private ObservableCollection<string> _itemsList;
    private int _selectedItemIndex;
    private ICommand _removeItem;

    public MainWindowViewModel()
    {
    // never interact with fields outside of the property 'set' clause
    // use property name instead of back-end field
    ItemsList = new ObservableCollection<string> { "1", "2", "3", "4" };
    }

    public ObservableCollection<string> ItemsList
    {
    get => _itemsList;
    set
    {
    _itemsList = value;
    OnPropertyChanged(); // Notify UI that property was changed

    //other ways doing the same call
    // OnPropertyChanged("ItemsList");
    // OnPropertyChanged(nameof(ItemsList));
    }
    }

    public int SelectedItemIndex
    {
    get => _selectedItemIndex;
    set
    {
    _selectedItemIndex = value;
    OnPropertyChanged();
    }
    }

    // command will be initialized in "lazy" mode, at a first call.
    public ICommand RemoveItem => _removeItem ?? (_removeItem = new RelayCommand(parameter =>
    {
    ItemsList.RemoveAt(SelectedItemIndex);
    },
    // SelectedItemIndex -1 means nothing is selected
    parameter => SelectedItemIndex >=0 && ItemsList.Count > 0));
    }

    作为奖励,您可以通过编程方式更改 SelectedIndexListView只需将任何值设置为 SelectedItemIndex .

    编辑:

    抱歉,我忘记在删除后保留选择。修改命令:

    public ICommand RemoveItem => _removeItem ?? (_removeItem = new RelayCommand(parameter =>
    {
    int index = SelectedItemIndex;
    ItemsList.RemoveAt(index);
    if (ItemsList.Count > 0)
    SelectedItemIndex = (index == ItemsList.Count) ? index - 1 : index;
    }, parameter => SelectedItemIndex >= 0 && ItemsList.Count > 0));

    关于c# - 从代码中突出显示 ListView 项 - WPF 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61538222/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com