gpt4 book ai didi

c# - CommandParameter 始终为空 wpf MVVM

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

我想得到 NamePlaylistItem我点击一个MenuContext。但是参数总是空的,我不知道为什么。

这是 ListView 中的菜单

XML

<MenuItem Header="Add" ItemsSource="{Binding Path=ItemSourcePlaylist}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding TestCall}" CommandParameter="{Binding NamePlaylist}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<MenuItem.ItemTemplate>
<DataTemplate>
<TextBlock Name="NamePlaylistText" Text="{Binding Path=NamePlaylist}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>

命令提供者
public class CommandProvider : ICommand
{
#region Constructors

public CommandProvider(Action<object> execute) : this(execute, null) { }

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

#endregion

#region ICommand Members

public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}

public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}

public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}

#endregion

private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}

调用
public ICommand TestCall { get { return new RelayCommand(obj => this._settingsFunction.TestFunction(obj)); } }

功能
public void TestFunction(object o)
{
var tmp = o as string;
Console.WriteLine(tmp);
Console.WriteLine("TestMdr");
}

最佳答案

如果我了解您的 View 模型,那么 ItemSourcePlaylistTestCall属于一类和NamePlaylistItemSourcePlaylist 的属性(property)元素。如果是这种情况,我建议使用 ItemsContainerStyle并绑定(bind)Command parent 的属性(property)DataContextCommandParameter到当前项目的 DataContext

<MenuItem Header="Add" ItemsSource="{Binding Path=ItemSourcePlaylist}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type MenuItem}}, Path=DataContext.TestCall}"/>
<Setter Property="CommandParameter" Value="{Binding NamePlaylist}"/>
</Style>
</MenuItem.ItemContainerStyle>
<MenuItem.ItemTemplate>
<DataTemplate>
<TextBlock Name="NamePlaylistText" Text="{Binding Path=NamePlaylist}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>

关于c# - CommandParameter 始终为空 wpf MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597812/

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