WPF 单击标签更改复选框 isChecked 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15087124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF click on label change checkbox isChecked property
提问by sandkasten
I'm new to WPF and try (in my opinion) an easy task but I didn't get it. Even Google won't help me, or I asked the wrong question.
我是 WPF 的新手并尝试(在我看来)一项简单的任务,但我没有得到它。甚至谷歌也帮不了我,或者我问错了问题。
I have a checkbox and a label; I wish that a click on the label change the isCheckedproperty of the checkbox.
我有一个复选框和一个标签;我希望单击标签可以更改isChecked复选框的属性。
I want to do this completely in XAML with no code behind, because I wish to keep the code behind file clean of unnecessary code. Please don't discuss on this point. I know it's a single line of code doing this in code behind!
我想在没有代码的情况下完全在 XAML 中执行此操作,因为我希望保持文件背后的代码没有不必要的代码。请不要讨论这个问题。我知道这是在后面的代码中执行此操作的单行代码!
Working with event setter on the label doesn't solve the problem because you can only set the handler (which is in code behind of course). Using a storyboard doesn't help because there is no way to check the actual value of the property.
在标签上使用事件设置器并不能解决问题,因为您只能设置处理程序(当然,这是在代码后面)。使用故事板无济于事,因为无法检查属性的实际值。
Does anyone have a good hint? Maybe I overlooked something. Please provide some code snippet for the solution.
有没有人有好的提示?也许我忽略了一些东西。请提供一些解决方案的代码片段。
采纳答案by Danield
Paste this code into kaxaml
将此代码粘贴到kaxaml中
You'll see that clicking on the label toggles the checkbox.
您会看到单击标签会切换复选框。
[See this SO answerby Kent]
[请参阅Kent 的这个SO 答案]
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<CheckBox IsChecked="{Binding IsChecked, ElementName=checkbox}" Content="Hello">
<CheckBox.Template>
<ControlTemplate TargetType="CheckBox">
<ContentPresenter/>
</ControlTemplate>
</CheckBox.Template>
</CheckBox>
<CheckBox x:Name="checkbox" Content="A normal checkbox"/>
</StackPanel>
</Page>
回答by mikelt21
You can also do this:
你也可以这样做:
<CheckBox>
<Label Content="Your text here"/>
</CheckBox>
One limitation though is that the text will have to be on the right side of the checkbox.
但一个限制是文本必须位于复选框的右侧。

