gpt4 book ai didi

c# - MVVM Light EventToCommand - 无法触发事件

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:49 26 4
gpt4 key购买 nike

我已经阅读了论坛上为 EventToCommand 提供的每个答案,但无法触发我的事件。这是构成我的问题的代码片段。我使用的是 Visual Studio 2015 社区版。

用户控件声明:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight"


<UserControl.DataContext>
<vm:MenuTreeViewModel></vm:MenuTreeViewModel>
</UserControl.DataContext>

<syncfusion:TreeViewAdv x:Name="treeMain" Width="340" Margin="10,0,0,0"
ItemsSource="{Binding Collection, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Grid.ColumnSpan="1"
VisualStyle="ShinyBlue" FontFamily="Verdana" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Top" VerticalAlignment="Top"
HorizontalAlignment="Left" FontSize="11" Height="768"
ScrollViewer.VerticalScrollBarVisibility="Auto" Visibility="Visible">

<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<cmd:EventToCommand Command="{Binding DataContext.SelectedItemChanged,
ElementName=treeMain, Mode=OneWay}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>

我的 ViewModel 逻辑:

MenuTreeViewModel代码:

public void SelectedItemChanged(object sender,  
RoutedPropertyChangedEventArgs<object> e)
{
if (e.NewValue is Models.MenuTree)
{
// This is the Top Level Clients item
// Nothing needs to be done.
// clear out Current items of all Model types
// MenuTree tree = (MenuTree)e.NewValue;

}
if (e.NewValue is Models.Provider)
{
//MessageBox.Show("Provider";
// Set CurrentProvider to the selected item.
Dal db = new Dal();
}
if (e.NewValue is Models.Batch)
{
MessageBox.Show("Batch");
}
if (e.NewValue is Models.Consumer)
{
MessageBox.Show("Consumer");
}
}
}

我知道我一定遗漏了什么。有人可以帮忙吗?

谢谢。

戴夫·K

最佳答案

@Rachel 是对的

您正在使用 MvvmLight,因此请使用内置的中继命令。将它放在您的 View 模型中并绑定(bind)到公共(public)属性 MyCommand 或您将其重命名为的任何内容。

public RelayCommand MyCommand 
{
get;
private set;
}

public MainViewModel()
{
MyCommand = new RelayCommand(
ExecuteMyCommand,
() => _canExecuteMyCommand);
}

private void ExecuteMyCommand()
{
// Do something
}

你需要做一些阅读以确保你理解这一点,因为你不应该在 MVVM 中使用 VM 相关功能的控制事件

看看HERE

关于c# - MVVM Light EventToCommand - 无法触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507961/

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