gpt4 book ai didi

WPF ContextMenu Dictionary> 数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-01 06:46:55 25 4
gpt4 key购买 nike

假设以下类定义。


public enum ContentType { Playlist, Audio, Video, Picture }

public interface IDataProvider
{
string Name
{
get;
}
}

public class ProviderList : List<IDataProvider>
{
}

public class MainViewModel
{
public Dictionary<ContentType, ProviderList> ProvidersDictionary;

public MainViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
// Code runs "for real"
this.ProvidersDictionary = new Dictionary<ContentType, ProviderList>();
ProviderList providerList = new ProviderList();
providerList.Add(new DataProvider());
this.ProvidersDictionary.Add(ContentType.Audio, providerList);
providerList = new ProviderList(providerList);
providerList.Add(new DataProvider());
this.ProvidersDictionary.Add(ContentType.Video, providerList);
}
}
}

因此,此 ProvidersDictionary 属性绑定(bind)到 Window 上下文菜单,如下所示:

<Window.ContextMenu>
<ContextMenu ItemsSource="{Binding ProvidersDictionary}">
<ContextMenu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Value}">
<TextBlock Margin="1" Text="{Binding Key}" Height="20"/>

<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</Window.ContextMenu>

问题是:如何使 DataProvider 菜单项的 ICommand 数据绑定(bind)单击并在命令的 Execute 方法中检索数据类型(枚举类型)和数据提供者(IDataProvider 接口(interface))。



更新
我想让一些命令类绑定(bind)到 MenuItems,例如:

class DataProviderMenuSelectCommand : ICommand
{
#region ICommand Members

public void Execute(object parameter)
{
ContentTypeProviderPair contentProviderPair = parameter as ContentTypeProviderPair;
if (contentProviderPair != null)
{
// contentProviderPair.Type property - ContentType
// contentProviderPair.Provider property - IProvider
}
}
}

MainViewModel 会将此命令类的实例作为属性公开。

最佳答案

问题已解决:

<UserControl x:Class="DataProvidersView"
...

<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Path=DataContext.DataProviderSwitchCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vw:DataProvidersView}}}" />
<Setter Property="CommandParameter">
<Setter.Value>
<MultiBinding>
<Binding Path="DataContext.Key"
RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" />
<Binding />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.ItemContainerStyle>
</UserControl>

关于WPF ContextMenu Dictionary<Key, List<Value>> 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4131597/

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