简体   繁体   中英

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 ). To make matters worse, no Exceptions are thrown at all. 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. Padding property is of type Thickness and Text property is 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 . In XAML the compiler internally translates the string "0,0,2,2" to Thickness object. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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