简体   繁体   English

从代码隐藏创建绑定不起作用C#XAML

[英]Creating Binding from Code-Behind not working C# XAML

屏幕截图
I have the following code that creates a binding in code-behind. 我有以下代码在代码隐藏中创建绑定。 However, it does not seem to work (when the text in PageMarginTextBox is changed, nothing happens, and when the app is loaded, the Padding of newPage is not set to the text of PageMarginTextBox ). 但是,它似乎不起作用(当更改PageMarginTextBox的文本时,什么也没有发生,并且在加载应用程序时, newPagePadding未设置为PageMarginTextBox的文本)。 To make matters worse, no Exceptions are thrown at all. 更糟的是,根本不会引发任何Exceptions All elements have been defined earlier on. 所有元素已在前面定义。

Binding pageMarginBinding = new Binding
{
    Source = PageMarginTextBox,
    Path = new PropertyPath("Text"),
};
newPage.SetBinding(ContentControl.PaddingProperty, pageMarginBinding);
//PageMarginTextBox.Text determines the Padding of newPage

How can I fix this? 我怎样才能解决这个问题? Any solutions would be appreciated. 任何解决方案将不胜感激。 Thanks! 谢谢!

You are trying to Bind PaddingProperty to text. 您正在尝试将PaddingProperty绑定到文本。 Padding property is of type Thickness and Text property is String . 填充属性的类型为Thickness ,文本属性为String

I am not sure whether you want to bind padding / text, just giving you an idea if you want to bind the Padding. 我不确定是否要绑定填充/文本,只是想让您知道是否要绑定填充。

Binding pageMarginBinding = new Binding
{
    Source = PageMarginTextBox,
    Path = new PropertyPath("Padding"),
};
newPage.SetBinding(ContentControl.PaddingProperty, pageMarginBinding);

Your problem is because you are trying to assign a string to a Thickness . 您的问题是因为您试图将一个string分配给Thickness In XAML the compiler internally translates the string "0,0,2,2" to Thickness object. 在XAML中,编译器在内部将字符串“ 0,0,2,2”转换为Thickness对象。 But in code behind you have to write the code for the conversion yourself. 但是在后面的代码中,您必须自己编写用于转换的代码。

ThicknessConverter myThicknessConverter = new ThicknessConverter();
PageThickness= (Thickness)myThicknessConverter.ConvertFromString(PageMarginTextBox.Text);

Then you have to bind this to your control. 然后,您必须将此绑定到您的控件。 Again this is only half the solution. 同样,这只是解决方案的一半。 You need to wire this up with the Binding. 您需要使用绑定将其连接起来。

private Thickness _pageThickness;
public Thickness PageThickness
{
get
 {
   return _pageThickness;
 }
set
 {
  _pageThickness = value;
  NotifyPropertyChanged("PageThickness");
 }

Then you probably can bind it in XAML 然后,您可以将其绑定到XAML中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM