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

标签 wpf mvvm commandbinding

在我看来,我使用 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/

相关文章:

c# - 如何在 wpf 应用程序的配置文件中将自定义属性添加到 tracelistener

c# - WPF Dispatcher BeginInvoke 排序保证

.net - WPF 应用程序大小与 Winforms 应用程序大小

WPF - 为以编程方式添加的 GridViewColumns 设置 DataTemplate

WPF 菜单项快捷方式。奇怪的行为

wpf - 如何在 WPF 中将按钮绑定(bind)到 DataGrid 删除命令

c# - 在哪里提出 NotifyPropertyChanged?

wpf - WPF从单个 View 模型打印多页

c# - Mvvm后退按钮: Page and ViewModel lose command binding

c# - MVVM 和自定义命令?