【问题标题】:Call Command from another class (WPF, Mvvm)从另一个类(WPF,Mvvm)调用命令
【发布时间】:2017-08-14 08:57:54
【问题描述】:

我制作了一个带有复选框的列表框。 Listbox 绑定到我的 Checkbox 类的列表。现在,当我选中/取消选中复选框时,我想从我的 DataContext 而不是我的 Checkbox 类中调用一个命令

        <ListBox Grid.Column="1" ItemsSource="{Binding Databases}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"></StackPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Margin="5 5 0 0" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

复选框类:

public class CheckBoxDatabase
{
    private string name;
    protected bool isChecked;
    public ObservableCollection<CheckBoxDatabase> Owner;

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            setzeChecked(value);
            NotifyPropertyChanged();
        }

    }

    public virtual void setzeChecked(bool value)
    {
        isChecked = value;
    }


    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged();
        }
    }

    #region NotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

我的主要问题是如果我添加一个命令,它会告诉我在类中找不到它(当然因为我希望它在我有中继命令的数据上下文类中调用它。(还有另一个中继命令独立于我所做的所有这些工作)

【问题讨论】:

  • 你为什么要删除复选框类的代码?
  • 我认为它不相关,如果需要我可以再次添加它
  • @PhilipK 请添加
  • @Mitya 我读了它,还添加了更多说明。希望它有所帮助:)
  • @PhilipK,我在代码示例中没有看到任何命令。请编辑问题并包含 Command/DataContext 定义

标签: c# wpf mvvm


【解决方案1】:

如果您想绑定到定义了Databases 源集合的类的ICommand 属性,您可以使用RelativeSource:

<CheckBox Content="{Binding Name}" Command="{Binding DataContext.YourCommandProperty, RelativeSource={RelativeSource AncestorType=ListBox}}" Margin="5 5 0 0" />

将YourCommandProperty 替换为您的属性的实际名称。

【讨论】:

  • 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2017-02-26
  • 1970-01-01
相关资源
最近更新 更多