C# 为每个代码隐藏的附加属性添加数据绑定

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

Add DataBinding for attached Property per Code Behind

c#data-bindingcode-behindattached-properties

提问by Taladan

I want to add a DataBinding per Codebehind for an attached Property and want to show the Canvas.Leftproperty in a TextBox. How do I add this property?

我想为附加的属性添加每个代码隐藏的数据绑定,并希望Canvas.Left在文本框中显示该属性。如何添加此属性?

采纳答案by ageektrapped

It's somewhat unclear from your question, but I think you're asking how one would bind to the attached property Canvas.Leftand show it in a TextBox. I'll assume you want it for a control other than the TextBox.

从您的问题中有点不清楚,但我认为您是在问如何绑定到附加属性Canvas.Left并将其显示在 TextBox 中。我假设您希望它用于 TextBox 以外的控件。

<Canvas>
   <TextBox x:Name="textBox" Text="{Binding ElementName=button, Path=(Canvas.Left)}" />
   <Button x:Name="button" Content="Press me" />
</Canvas>

Note the brackets around the attached property.

请注意附加属性周围的括号。

EDIT: To do the equivalent in code, use the following:

编辑:要在代码中执行等效操作,请使用以下内容:

Binding binding = new Binding();
binding.Source = button;
binding.Path = new PropertyPath(Canvas.LeftProperty);
textBox.SetBinding(TextBlock.TextProperty, binding);

回答by Taladan

Yes, a canvas has no left property. it is a attached property for a FrameworkItem in a Canvas Content.

是的,画布没有左属性。它是画布内容中 FrameworkItem 的附加属性。

<Canvas Width="100" Height="100">
   <TextBox Name="top" Canvas.Left="12"></TextBox>
</Canvas>