将按钮的IsEnabled属性绑定到数据网格中的选定项目的最佳做法是什么?

时间:2010-11-06 14:51:37

标签: wpf binding

我在数据网格中的所选项目上有一个数据网格和许多命令按钮。

将根据网格中所选项目中的属性隐藏或禁用这些按钮。

例如:如果所选记录为IsNew,则将禁用“取消”按钮。

实施这种情况的最佳做法是什么?

我可以手动在SelectedItemChange中实现它,如下所示:

void myGrid_selectedItemChanged(sender, args..)
{
    cancelButton.IsEnabled = SelectedItem.IsNew ; // just an example
}

这种方法的问题在于,当删除所选项目时,不会触发此事件。

或者在XAML中,使用控件绑定依赖项属性:

<!--SelectedItemIsNew is a property in the form and binding it with IsEnabled... -->
<Button x:Name="cancelButton" IsEnabled="{Binding SelectedItemIsNew ...}"/>

这里的问题,我必须为属性赋值以通知绑定控件,或者换句话说,这里的代码是什么来更改属性的值?

另一种选择!

3 个答案:

答案 0 :(得分:1)

这一定是正确的:

<Button x:Name="cancelButton" IsEnabled="{Binding IsNew, Source=SelectedItem}"/>

问题是,您的SelectedItem在哪里?它是DataContext的属性,还是控件的属性(或控件中的某些列表)?

编辑:
对于Control属性,应执行以下操作:

<Button x:Name="cancelButton"
        IsEnabled="{Binding SelectedItem.IsNew,
                            RelativeSource={RelativeSource FindAncestor, AncestorType=local:MyControl}}"/>

答案 1 :(得分:1)

MVVM实现看起来像这样......

查看型号代码:

public class ParentViewModel : ViewModel
{
    private readonly ICommand cancelCommand;
    private readonly ICollection<ChildViewModel> children;
    private ChildViewModel selectedChild;

    public ParentViewModel()
    {
        this.cancelCommand = new DelegateCommand(this.OnCancel, this.CanCancel);
        this.children = new ObservableCollection<ChildViewModel>();
    }

    public ICommand CancelCommand
    {
        get { return this.cancelCommand; }
    }

    public ICollection<ChildViewModel> Children
    {
        get { return this.children; }
    }

    public ChildViewModel SelectedChild
    {
        get { return this.selectedChild; }
        set
        {
            if (this.selectedChild != value)
            {
                this.selectedChild = value;
                this.OnPropertyChanged(() => this.SelectedChild);
            }
        }
    }

    private void OnCancel(object parameter)
    {
        // cancel logic here
    }

    private bool CanCancel(object parameter)
    {
        // can only cancel if there's a child selected
        return this.SelectedChild != null;
    }
}

XAML:

<GridView ItemsSource="{Binding Children}" SelectedItem="{Binding SelectedChild}">
    ...
</GridView>

...

<Button Command="{Binding CancelCommand}" Content="Cancel"/>

答案 2 :(得分:0)

嘿,我有一段时间回到同样的情况,我总是这样做,当我用SL / WPF中的网格或列表绑定一些数据时,因为它很容易且更容易理解。为什么不试试Binding coustom list到你的代码?对于例如..采取和提起像字符串HyperLinkNaviagtion

当您从服务中获取值时,然后将列表分配给您的网格,迭代所有项目并为HyperLinkNaviagtion分配一些值,如

 if(SomeCondition)
    { 
      // navigaet to google
          HyperLinkNaviagtion ="www.google.com";
    } 
 else 
   { 
     // navigaet to yahoo
       HyperLinkNaviagtion ="www.yahoo.com";
   }

在Xaml中,执行以下操作

NavigateUri =“{Binding HyperLinkNaviagtion}”

这是唐,你几乎可以控制这样的东西=) 这可能不是最好的,但在我的情况下,它也是最容易和无张力的。