【问题标题】:Bind ICommand in Converter在转换器中绑定 ICommand
【发布时间】:2014-01-27 08:40:25
【问题描述】:

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

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

在我的视图的视图模型中,我有一个可以处理按钮单击的 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 中的命令分配给创建按钮的转换器中的命令?

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

【问题讨论】:

  • 转换器不用于此目的

标签: wpf mvvm commandbinding


【解决方案1】:

您可以通过 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 必须是字符串,不能是数据绑定的。

【讨论】:

  • 如果我只有一个按钮,这个解决方案就可以工作。但在我的情况下,按钮是在运行时创建的
  • 很高兴听到,也许您想编辑您的原始帖子并分享您的解决方案。
【解决方案2】:

我自己解决了。

我刚刚创建了一个单例类,其中 ViewModel 的命令在构造函数中传递。在调用转换器的那一刻,singelton 已经有了命令,转换器可以分配命令。

【讨论】:

  • 但实际上您应该为此使用数据模板。数据模板应该有一个与 viewmodel.command 绑定的按钮。
猜你喜欢
  • 2012-04-11
  • 2011-01-17
  • 2015-04-02
  • 2016-04-23
  • 1970-01-01
  • 2015-11-13
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多