开发者

How do I make a ControlTemplate (for a checkbox) readonly in WPF/MVVM?

I've got a WPF datagrid where I've created a ControlTemplate for a checkbox to represent a bool? type. I'd like for the checkbox/control template to readonly to the user, but be able to change the value

Here's the template:

<ControlTemplate x:Key="checkboxTemplate" TargetType="CheckBox">
    <Grid Background="{TemplateBinding Background}" Height="{TemplateBinding Height}">
        <Rectangle x:Name="r" Height="10" Width="40" HorizontalAlignment="Center" VerticalAlignment="Center" RadiusX="4" RadiusY="4"></Rectangle>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="CheckBox.IsChecked" Value="True">
            <Setter Property="Fill" Value="#FF66D660" TargetName="r"></Setter>
        </Trigger>
        <Trigger Property="CheckBox.IsChecked" Value="False">
            <Setter Property="Fill" Value="#FFD50005" TargetName="r"&g开发者_运维百科t;</Setter>
        </Trigger>
        <Trigger Property="CheckBox.IsChecked" Value="{x:Null}">
            <Setter Property="Fill" Value="SlateGray" TargetName="r"></Setter>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Here's the implementation in the datagrid:

<DataGridTemplateColumn SortMemberPath="IsReady" Header="Ready" CanUserSort="True" IsReadOnly="True">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsReady, Mode=OneWay}" HorizontalAlignment="Center" Template="{StaticResource checkboxTemplate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


You can either set IsHitTestVisible="false" or IsEnabled="false" on the checkbox.


Easiest way to make it readonly to move it behind some control with almost transparent background.

<DataTemplate>
  <Border Opacity="0.01" Background="White">
   <CheckBox IsChecked="{Binding IsReady, Mode=OneWay}" HorizontalAlignment="Center" Template="{StaticResource checkboxTemplate}" />
  </Border>
</DataTemplate>


If you're editing the Checked value from code, you should be editing the binding source (IsReady), and not the CheckBox.Checked value. Setting MyCheckBox.Checked will overwrite the binding, and not save the change to your IsReady property.

It's preferred to change the IsReady property from your ViewModel, but if you must do it from behind the View I usually cast the CheckBox's DataContext to my data object, and set the bound property from there

Something like this:

((MyDataObject)MyCheckBox.DataContext).IsReady = false;

As for making a CheckBox read-only to the user, set it's IsEnabled property to false

<CheckBox x:Name="MyCheckBox" IsEnabled="False" IsChecked="{Binding IsReady}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜