C# 如何将控件的属性绑定到另一个控件的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9586956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:01:37  来源:igfitidea点击:

How to bind a control's property to another control's property?

c#.netwpfbindingproperties

提问by Jader Dias

I want that the SaveButton from my form to dissapear when the form is disabled. I do that this way:

我希望表单中的 SaveButton 在表单被禁用时消失。我这样做:

this.formStackPanel.IsEnabled = someValue;
if(this.formStackPanel.IsEnabled)
{
    this.saveButton.Visibility = Visibility.Visible;
}
else
{
    this.saveButton.Visibility = Visibility.Collapsed;
}

Isn't there a way of binding those properties in the XAML? Is there a better way of doing that?

没有办法在 XAML 中绑定这些属性吗?有没有更好的方法来做到这一点?

采纳答案by Matt Burland

Yes. You should be able to bind the stackpanel's IsEnabled to your button's Visibility property. However, you need a converter. WPF comes with a BooleanToVisibilityConverter class that should do the job.

是的。您应该能够将堆栈面板的 IsEnabled 绑定到按钮的 Visibility 属性。但是,您需要一个转换器。WPF 带有一个 BooleanToVisibilityConverter 类,应该可以完成这项工作。

<Window
  x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
  </Window.Resources>
  <StackPanel>
    <ToggleButton x:Name="toggleButton" Content="Toggle"/>
    <TextBlock
      Text="Some text"
      Visibility="{Binding IsChecked, ElementName=toggleButton, Converter={StaticResource BooleanToVisibilityConverter}}"/>
  </StackPanel>
</Window>