Silverlight数据网格禁用特定单元格

时间:2012-12-06 14:27:10

标签: .net silverlight validation datagrid silverlight-4.0

必须在silverlight的DataGrid元素中进行验证:如果在组合框中选择了特定值,则必须禁用同一行(DataGridCheckBoxColumn)上的复选框列。但是,从我看到的情况来看,我只能禁用整个列,这是不可接受的

那么,如果我有其坐标(行,列),如何禁用特定单元格?

P.S。类似的问题 - here不适合我。 silverlight 4中有没有CellEnter和CellLeave事件

1 个答案:

答案 0 :(得分:2)

答案的一部分可能是:

private void DisableCheckboxColumnInRow(DataGridRow row)
{
    var checkBoxColumn = Datagrid1.Columns[0];
    var checkBoxCell = GetCell(checkBoxColumn, row);
    checkBoxCell.IsEnabled = false;
}

private static DataGridCell GetCell(DataGridColumn column, DataGridRow row)
{
    var cellContent = column.GetCellContent(row);
    return (DataGridCell)cellContent.Parent;
}

但是使用MVVM可能有更好的方法:

ViewModel部分:

public class TestItem : INotifyPropertyChanged
{
    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            _isChecked = value;
            OnPropertyChanged("IsChecked");
        }
    }

    private bool _canBeChecked;
    public bool CanBeChecked
    {
        get { return _canBeChecked; }
        private set
        {
            _canBeChecked = value;
            OnPropertyChanged("CanBeChecked");
        }
    }

    private string _selectedValue;
    public string SelectedValue
    {
        get { return _selectedValue; }
        set
        {
            _selectedValue = value;
            OnPropertyChanged("SelectedValue");
            // here we do the 'magic':
            CanBeChecked = SelectedValue != "one";
        }
    }

    public IEnumerable<string> PossibleValues
    {
        get
        {
            yield return "one";
            yield return "two";
            yield return "free";
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

查看部分:

<Controls:DataGridTemplateColumn>
    <Controls:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding PossibleValues}" SelectedItem="{Binding SelectedValue,Mode=TwoWay}" />
        </DataTemplate>
    </Controls:DataGridTemplateColumn.CellTemplate>
</Controls:DataGridTemplateColumn>
<Controls:DataGridTemplateColumn>
    <Controls:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsChecked,Mode=TwoWay}" IsEnabled="{Binding CanBeChecked}" />
        </DataTemplate>
    </Controls:DataGridTemplateColumn.CellTemplate>
</Controls:DataGridTemplateColumn>