0

我想在我的属性为 Null 时禁用我的网格,并在 Not null 时启用我的网格。

在我的 .XAML 中:

  <Grid Grid.Row="2" IsEnabled="{Binding ElementName=dgCustomers, Path=SelectedItem}">
      <my:ProductsHistoryDetailView />
  </Grid>

在我的 ViewModel.cs 中:

    public ProductHistory SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (_SelectedItem != value)
            {
                _SelectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
            }
        }
    }
4

4 回答 4

7

您应该为您的视图模型添加一个额外的属性。

    public bool IsGridEnabled
    {
        get 
          { 
             return this.SelectedItem != null;
          }
    }

<Grid Grid.Row="2" IsEnabled="{Binding IsGridEnabled}">
     <my:ProductsHistoryDetailView />
</Grid>

当您SelectedItem进行更改时,请调用 OnPropertyChanged 事件IsGridEnabled

public ProductHistory SelectedItem
{
    get { return _SelectedItem; }
    set
    {
        if (_SelectedItem != value)
        {
            _SelectedItem = value;
            RaisePropertyChanged(() => SelectedItem);
            RaisePropertyChanged(() => IsGridEnabled);
        }
    }
}
于 2013-12-23T15:33:42.003 回答
3

使用样式触发器来更改 Enabled 属性,而不是尝试直接绑定它

<Grid Grid.Row="2">
    <Grid.Style>
        <Style TargetType="Grid">
           <Setter Property="IsEnabled" Value="True"/>
           <Style.Triggers>
               <DataTrigger Binding="{Binding ElementName=dgCustomers, Path=SelectedItem"}" Value={x:Null}>
                    <Setter Property="IsEnabled" Value="False"/>
               </DataTrigger>
           </Style.Triggers>            
        </Style>
    </Grid.Style>
</Grid>
于 2013-12-23T23:21:35.927 回答
2

您可以使用IValueConverter

<Grid Grid.Row="2" IsEnabled="{Binding 
    ElementName=dgCustomers, Path=SelectedItem, 
    Converter={StaticResource NullToFalseConverter}">

public class NullToFalseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? false : true;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

或者,将另一个属性添加到您的视图模型可能更容易IsSelected,您可以直接绑定到IsEnabled

public bool IsSelected
{
    get { return _isSelected; }
    set
    {
        if (_isSelected != value)
        {
            _isSelected = value;
            RaisePropertyChanged(() => IsSelected);
        }
    }
}

public ProductHistory SelectedItem
{
    get { return _SelectedItem; }
    set
    {
        if (_SelectedItem != value)
        {
            _SelectedItem = value;
            RaisePropertyChanged(() => SelectedItem);
        }
        IsSelected = value != null;
    }
}
于 2013-12-23T15:30:17.903 回答
1

请确保您的 selectebitem 具有如下有效值:

<Grid Grid.Row="2" IsEnabled="{Binding ElementName=dgCustomers, Path=SelectedItem.Value}">
      <my:ProductsHistoryDetailView />
  </Grid>
于 2013-12-23T15:28:39.223 回答