亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

WPF將UI事件綁定到ViewModel中的命令

WPF將UI事件綁定到ViewModel中的命令

C#
瀟瀟雨雨 2019-08-12 18:05:26
WPF將UI事件綁定到ViewModel中的命令我正在做一些簡單的應用程序重構以跟隨MVVM,我的問題是如何將SelectionChanged事件從我的代碼中移出到viewModel?我已經看了一些綁定元素到命令的例子,但是并沒有完全掌握它。誰能幫忙解決這個問題。謝謝!有人可以使用下面的代碼提供解決方案嗎?非常感謝!public partial class MyAppView : Window {     public MyAppView()     {         InitializeComponent();         this.DataContext = new MyAppViewModel ();         // Insert code required on object creation below this point.     }     private void contactsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)     {         //TODO: Add event handler implementation here.                    //for each selected contact get the labels and put in collection          ObservableCollection<AggregatedLabelModel> contactListLabels = new ObservableCollection<AggregatedLabelModel>();         foreach (ContactListModel contactList in contactsList.SelectedItems)         {             foreach (AggregatedLabelModel aggLabel in contactList.AggLabels)             {                 contactListLabels.Add(aggLabel);             }         }         //aggregate the contactListLabels by name         ListCollectionView selectedLabelsView = new ListCollectionView(contactListLabels);         selectedLabelsView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));         tagsList.ItemsSource = selectedLabelsView.Groups;     }}
查看完整描述

3 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

您應該EventTriggerInvokeCommandActionWindows.Interactivity命名空間結合使用。這是一個例子:

<ListBox ...>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers></ListBox>

你可以System.Windows.Interactivity去參考Add reference > Assemblies > Extensions。

完整的i命名空間是:xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"


查看完整回答
反對 回復 2019-08-12
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

我處理這個問題的方法是在ViewModel中有一個SelectedItem屬性,然后將ListBox的SelectedItem綁定到該屬性。


查看完整回答
反對 回復 2019-08-12
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

要重構這個,你需要改變你的想法。您將不再處理“選擇已更改”事件,而是將所選項目存儲在viewmodel中。然后,您將使用雙向數據綁定,以便在用戶選擇項目時更新您的viewmodel,并在更改所選項目時更新您的視圖。


查看完整回答
反對 回復 2019-08-12
  • 3 回答
  • 0 關注
  • 1822 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號