gpt4 book ai didi

wpf - 在转换器中绑定(bind) ICommand

转载 作者:行者123 更新时间:2023-12-03 10:17:40 28 4
gpt4 key购买 nike

在我看来,我使用 ItemsControl 来显示几个按钮。 ItemsControl 的 XAML 是:

<ItemsControl ItemsSource="{Binding CustomDirectories, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource buttonConverter}}" Margin="2">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

在我的 View 的 View 模型中,我有一个可以处理按钮单击的 ICommand。我需要这里的命令,因为这里还需要一些其他的属性。

创建按钮的转换器是:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ObservableCollection<DVDDirectory>)
{
ObservableCollection<CustomDirectory> customDirectories = (ObservableCollection<CustomDirectory>)value;
List<Button> buttons = new List<Button>();

foreach (CustomDirectory customDirectory in customDirectories)
{
Button button = new Button
{
Margin = new Thickness(2),
Width = 140,
Height = 25,
Content = Path.GetFileName(customDirectory.Path)
};
buttons.Add(button);
}
return buttons;
}
return value;
}

我现在的问题是:如何将 ViewModel 中的命令分配给创建按钮的转换器中的命令?

我试图将我的 View 的 DataContext 作为 ConverterParameter 传递给转换器,但我得到了一个 BindingException。

最佳答案

您可以通过 ElementName Binding 访问 View 的 DataContext:

<ItemsControl Name="MyItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Command="{Binding ElementName=MyItemsControl, Path=DataContext.MyCommand}" CommandParameter="{Binding}"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

ConverterParameter 必须是字符串并且不能是数据绑定(bind)的。

关于wpf - 在转换器中绑定(bind) ICommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21376240/

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