天天看點

WPF實作HTML的Label For CheckBox功能

HTML中的

label

控件通過将

for

屬性值設定為

checkbox

id

,實作

label

點選與

checkbox

的選中屬性關聯,但WPF中的

Label

控件卻沒有

For

屬性,我們可以通過如下方式實作此功能。

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
         xmlns:mit="clr-namespace:Mitov.PlotLab;assembly=Mitov.PlotLabBasic"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <CheckBox x:Name="chkManual" Grid.Column="0" HorizontalAlignment="Right" Margin="5" VerticalAlignment="Center" FontSize="16"/>
        <CheckBox Grid.Column="1" IsChecked="{Binding IsChecked, ElementName=chkManual}" Margin="5" Content="綁定測試" VerticalAlignment="Center" FontSize="16">
            <CheckBox.Template>
                <ControlTemplate TargetType="CheckBox">
                    <ContentPresenter/>
                </ControlTemplate>
            </CheckBox.Template>
        </CheckBox>
    </Grid>
</Window>
           

軟體運作效果:

WPF實作HTML的Label For CheckBox功能

參考資料:

https://stackoverflow.com/questions/6160566/change-a-labels-behavior-to-support-toggling-by-click-in-wpf/6161137#6161137