首页 > 其他分享 >WPF combobox selectionchanged and triggered the listbox scroll/locate to the selected item cooperate

WPF combobox selectionchanged and triggered the listbox scroll/locate to the selected item cooperate

时间:2024-04-08 20:57:59浏览次数:20  
标签:locate mvvm triggered Windows System private using null public

//xaml
<Window x:Class="WpfApp48.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"        
        xmlns:local="clr-namespace:WpfApp48"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="TextBlock" x:Key="tbStyle">
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Foreground" Value="Red"/>
            <Setter Property="FontWeight" Value="ExtraBold"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FontSize" Value="50"/> 
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0" x:Name="cbx" FontSize="30" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedIndex="0" DisplayMemberPath="Id" 
                  SelectedItem="{Binding CBXSelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding CbxChangeCommand}" CommandParameter="{Binding ElementName=dg}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ComboBox>
        <ListBox Grid.Row="2" x:Name="dg" ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedIndex="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <GroupBox BorderBrush="Blue" BorderThickness="3" Height="300" Width="1000" >
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <TextBlock Grid.Row="0" Text="{Binding Id}" Style="{StaticResource tbStyle}" />
                            <TextBlock Grid.Row="1" Text="{Binding Name}" Style="{StaticResource tbStyle}"/>
                            <TextBlock Grid.Row="2" Text="{Binding ISBN}" Style="{StaticResource tbStyle}"/>
                            <TextBlock Grid.Row="3" Text="{Binding Topic}" Style="{StaticResource tbStyle}"/>
                        </Grid>
                    </GroupBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp48
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = MainVM.GetVMInstance(this);
        }
    }
}

//viewmodel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;

namespace WpfApp48
{
    public class MainVM : INotifyPropertyChanged
    {
        private static MainVM VMInstance = null;
        private static object instanceLock = new object();
        public static MainVM GetVMInstance(Window winValue)
        {
            lock(instanceLock) 
            {
                if(VMInstance == null) 
                {
                    VMInstance=new MainVM(winValue);
                }
                return VMInstance;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged("BooksCollection");
                }
            }
        }

        private Book cBXSelectedBook;
        public Book CBXSelectedBook
        {
            get
            {
                return cBXSelectedBook;
            }
            set
            {
                if (value != cBXSelectedBook)
                {
                    cBXSelectedBook = value;
                    OnPropertyChanged("CBXSelectedBook");
                }
            }
        }
        
        static MainVM()
        {

        }
        private MainVM(Window winValue)
        {
            WinView = winValue;
            WinView.Loaded += WinView_Loaded;
        }

        private void WinView_Loaded(object sender, RoutedEventArgs e)
        {
            BooksCollection = new ObservableCollection<Book>();
            for(int i=0;i<1000;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = $"{i+1}_{Guid.NewGuid()}",
                    Name=$"Name_{Guid.NewGuid()}",
                    ISBN=$"ISBN_{Guid.NewGuid()}",
                    Title=$"Title_{Guid.NewGuid()}",
                    Topic=$"Topic_{Guid.NewGuid()}",
                });
            }
        }

        public Window WinView { get; set; }

        private DelegateCommand cbxChangeCommand;
        public DelegateCommand CbxChangeCommand
        {
            get
            {
                if(cbxChangeCommand == null)
                {
                    cbxChangeCommand = new DelegateCommand(CbxChangeCommandExecuted);
                }
                return cbxChangeCommand;
            }
        }

        private void CbxChangeCommandExecuted(object obj)
        {
            var lbx = obj as ListBox;
            if(lbx!=null && CBXSelectedBook!=null) 
            {
                lbx.ScrollIntoView(CBXSelectedBook);
            }
        }
    }

    public class Book
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set;}        
        public string Title { get; set;}
        public string Topic { get; set; }
    }

    public class DelegateCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public event EventHandler CanExecuteChanged;
        public void RaiseCanExecuteChanged() 
        {
            var handler = CanExecuteChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, EventArgs.Empty);
            }
        }

        public DelegateCommand(Action<object> executeValue,Predicate<object> canExecute)
        {
            _execute = executeValue;
            _canExecute = canExecute;
        }

        public DelegateCommand(Action<object> executeValue):this(executeValue, null) 
        {
        }

        public bool CanExecute(object parameter)
        {
            if(_canExecute==null)
            {
                return true;
            }
            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}

 

 

 

 

 

3Key part

1.Add System.Windows.Interactivity and reference in xaml

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  

2.Used the Interaction.Triggers,EventName InvokeCommandAction CommandParamete{Binding ElementName=lbx},the parameter can pass the listbox to viewmodel

 <i:Interaction.Triggers>
     <i:EventTrigger EventName="SelectionChanged">
         <i:InvokeCommandAction Command="{Binding CbxChangeCommand}" CommandParameter="{Binding ElementName=dg}"/>
     </i:EventTrigger>
 </i:Interaction.Triggers>

 

 

3.The scrolltoview() method to locate the selected item

private DelegateCommand cbxChangeCommand;
public DelegateCommand CbxChangeCommand
{
    get
    {
        if(cbxChangeCommand == null)
        {
            cbxChangeCommand = new DelegateCommand(CbxChangeCommandExecuted);
        }
        return cbxChangeCommand;
    }
}

private void CbxChangeCommandExecuted(object obj)
{
    var lbx = obj as ListBox;
    if(lbx!=null && CBXSelectedBook!=null) 
    {
        lbx.ScrollIntoView(CBXSelectedBook);
    }
}

 

标签:locate,mvvm,triggered,Windows,System,private,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18122535

相关文章

  • WPF datagrid mvvm multi select via customize datagrid
    usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;namespaceWpfApp39{publicclassMultiSelectDataGrid:D......
  • 在RichTextBox mvvm中使用wpf工具包在插入符号处插入文本
    ,可以通过以下步骤实现:首先,确保你已经在项目中引用了WPF工具包。可以通过在VisualStudio中的项目引用中添加对WPF工具包的引用来完成。在你的MVVM模式中,创建一个名为"InsertTextCommand"的命令类,用于处理插入文本的逻辑。这个命令类应该实现ICommand接口,并且包含一个Execute方......
  • mvvm
    classVue{constructor(options){/*视图的驱动*/this.$el=options.elthis._data=options.datathis.$options=optionsthis.$watchEvent={}console.log(document.querySelector(this.$el),this._data,this......
  • C#中的MVVM
    MVVM(Model-View-ViewModel)是一种设计模式,通常与WPF(WindowsPresentationFoundation)和Xamarin等框架结合使用,用于构建基于XAML的应用程序。MVVM是MVC模式的衍生,旨在进一步分离应用程序的逻辑和界面。以下是MVVM的知识点以及可能会在面试中被问到的一些问题和答案:MVVM的......
  • WAW导致write no-allocate复现
    禁用和开启dynamicmode,排除下干扰选定一个特定地址A,属性RA,WBWA,计算出其对应L1cache的SETnum,4路组相连发一次读地址A,allocate到L1连续发3个readallocate地址B/C/D,这些地址与A同SET,将该set填充满,但不能触发evict发2个写地址E/F,E与A同SET,为WBWA,F地址为WBWNA,触发e......
  • [C#] [WPF] MVVMToolkit入门案例心得
    跟着做的第一个MVVM项目,学到一点基础的东西,记下来;有些用词不准确假设我们要做一个页面,通过按钮来控制上方文本框的文字,通过勾选框来控制按钮的激活状态⬇️一般流程需要3个属性,2个私有属性,1个RelayCommand属性代表按钮点击后事件,并配有相应的getter/setter文本......
  • MVVM中ICommand的具体使用
    本节使用MVVM模式进行演示MyCommand为自定义的命令类,代码如下:publicclassMyComand:ICommand{privatereadonlyAction<object>_action;privatereadonlyFunc<object,bool>?_func;publicMyComand(Action<object>action,Func<object,bool>......
  • vue一些基础概念,核心理念,框架和库的区别,MVC和MVVM的区别,展示数据的几种方法、v-bind、
    1、什么是vue,核心理念,为什么学习vue1(单页面应用程序)用于构建用户界面的渐进式框架,采用自底向上增量开发的设计2数据驱动视图,组件化开发3轻量级框架、简单易学、虚拟的DOM、数据视图结构分离下面展示一些内联代码片。下面是vue的代码框架分为三部分:1.引入vue.js;2......
  • WPF MVVM模式ListBox下ContextMenu绑定Command的方法以及将所选的Item的数据传回去
    需求:ListBoxItem上右键,将数据传参。疑问:ContextMenu不继承DataContext,导致直接用RelativeSource找根的方式也绑定不到。解决方法:在ListBox.ContextMenu里写菜单,就可以直接绑定到ViewModel层的命令了,参数先用RelativeSource找到ContextMenu,再绑定PlacementTarget.SelectedItem。......
  • Vue的MVVM模式与双向绑定原理
    v-model 是Vue.js框架中用于实现双向数据绑定的指令。它充分体现了MVVM(Model-View-ViewModel)模式中的双向数据绑定特性。下面我们将详细解释 v-model 如何体现MVVM和双向绑定:1.MVVM模式MVVM模式是一种软件架构设计模式,它将应用程序分为三个部分:Model(模型):代表应用程......