【问题标题】:wpf toggle datagridcell read-onlywpf 切换 datagridcell 只读
【发布时间】:2013-11-24 01:54:45
【问题描述】:

我有一个数据网格,其中有一列即 Qty ,当用户按下表单上的“编辑”按钮时,用户只能输入数量(可编辑),否则它就像只读字段一样。

如何做到这一点?

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    如果您使用CheckBoxToggleButton,那么您只需使用Binding 就可以做到这一点,而无需任何代码:

    <ToggleButton Name="EditButton" Content="Edit" />
    ...
    <DataGrid ItemsSource="{Binding YourCollection}">
        <DataGrid.Columns>
            ...
            <DataGridTextColumn Header="Quantity" IsReadOnly="{Binding IsChecked, 
                ElementName=EditButton}" Binding="{Binding Quantity}" />
            ...
        </DataGrid.Columns>
    </DataGrid>
    

    更新>>>

    如果您使用类在DataGrid 中显示您的项目(这总是一个好主意),那么有一个简单的解决方案。您可以在IsReadOnly 属性中添加一个额外的bool 属性到Bind,并且您可以在每次更改Quantity 属性时更新bool 值:

    public string SerialNo
    {
        get { return serialNo; } 
        set
        {
            serialNo = value;
            NotifyPropertyChanged("SerialNo");
            // Update new property
            IsQtyReadOnly = serialNo == "The read only value";
        }
    }
    
    public bool IsQtyReadOnly // <<< New property
    {
        get { return isQtyReadOnly; } 
        set { isQtyReadOnly= value; NotifyPropertyChanged("IsQtyReadOnly"); }
    }
    

    还有 XAML:

    <ToggleButton Name="EditButton" Content="Edit" />
    ...
    <DataGrid ItemsSource="{Binding YourCollection}">
        <DataGrid.Columns>
            ...
            <DataGridTextColumn Header="Qty" IsReadOnly="{Binding IsQtyReadOnly}" 
                Binding="{Binding Qty}" />
            ...
        </DataGrid.Columns>
    </DataGrid>
    

    如果您这样做,IsQtyReadOnly 属性将在 SerialNo 属性值更改时自动更新。

    【讨论】:

    • 在我的要求中,我有 DataGridComboBox 列,即 SerialNo,如果用户从组合框中选择一个值,则 Qty 字段变为 readonly=true 否则 readonly=false
    【解决方案2】:

    您需要该按钮的事件处理程序:

    private void OnClick(object sender, RoutedEventArgs e)
    {
        QtyColumn.IsReadOnly = !QtyColumn.IsReadOnly;
    }
    

    【讨论】:

    • 不,是Qty这个栏目。
    猜你喜欢
    • 2011-04-20
    • 2011-02-26
    • 2016-08-29
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多