通过 XAML 创建的控件绑定正常,但通过代码创建的控件绑定不起作用。

huangapple go评论62阅读模式
英文:

Binding of the control created by xaml works fine, but binding of the control created by code does not work

问题

I will only translate the provided code for you:

// MainWindow.xaml.cs

namespace TestApp2
{
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
<!--MainWinodw.xaml-->

<Window x:Class="TestApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ex="using:TestApp2">
    <!--<ex:CustomButton/>-->
</Window>
// App.xaml.cs

namespace TestApp2
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var mainWindow = new MainWindow();
            mainWindow.Content = new CustomButton();
            mainWindow.Activate();
        }
    }
}
// CustomButton.cs

namespace TestApp2
{
    internal class CustomButton : Button
    {
        public object MyProperty
        {
            get => GetValue(MyPropertyProperty);
            set => SetValue(MyPropertyProperty, value);
        }
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register(nameof(MyProperty), typeof(object), typeof(CustomButton), new(null));

        public CustomButton()
        {
            SetBinding(ContentProperty, new Binding
            {
                Source = this,
                Path = new(nameof(MyProperty)),
            });

            // This code should always update the binding,
            // but it does not work if you create a control in the code.
            MyProperty = "Something";
        }
    }
}

Regarding the issue with the binding not working, it seems to be related to creating the control in code. When you create the control in XAML, the binding works fine, but when created in code, it doesn't update as expected. This could be due to differences in the timing of control initialization between XAML and code.

英文:
// MainWindow.xaml.cs

namespace TestApp2
{
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
&lt;!--MainWinodw.xaml--&gt;

&lt;Window x:Class=&quot;TestApp2.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:ex=&quot;using:TestApp2&quot;&gt;
    &lt;!--&lt;ex:CustomButton/&gt;--&gt;
&lt;/Window&gt;
// App.xaml.cs

namespace TestApp2
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var mainWindow = new MainWindow();
            mainWindow.Content = new CustomButton();
            mainWindow.Activate();
        }
    }
}
// CustomButton.cs

namespace TestApp2
{
    internal class CustomButton : Button
    {
        public object MyProperty
        {
            get =&gt; GetValue(MyPropertyProperty);
            set =&gt; SetValue(MyPropertyProperty, value);
        }
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register(nameof(MyProperty), typeof(object), typeof(CustomButton), new(null));

        public CustomButton()
        {
            SetBinding(ContentProperty, new Binding
            {
                Source = this,
                Path = new(nameof(MyProperty)),
            });

            // This code should always update the binding,
            // but it does not work if you create a control in the code.
            MyProperty = &quot;Something&quot;;
        }
    }
}

When you run the above code, only the null value, which is the value at the first binding, is loaded and not updated after that.

However, if you comment mainWindow.Content = new CustomButton(); out and uncomment &lt;!--&lt;ex:CustomButton/&gt;--&gt; to create it in xaml instead of in the code, the binding will work fine.

I tried setting the binding in the Loaded event because I thought it might be related to initialization, but the result was the same.

Why does the binding fail?

I'm trying to create inheritable pages or custom controls, so I'm trying to create controls and bindings from code without using xaml.

答案1

得分: 1

代码中的翻译部分如下:

"Instead you can use the property changed event:" -> "相反,您可以使用属性更改事件:"

internal class CustomButton : Button
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register(
            nameof(MyProperty),
            typeof(object),
            typeof(CustomButton),
            new PropertyMetadata(null, OnMyPropertyPropertyChanged));

    private static void OnMyPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is CustomButton customButton)
        {
            customButton.Content = e.NewValue;
        }
    }

    public object MyProperty
    {
        get => GetValue(MyPropertyProperty);
        set => SetValue(MyPropertyProperty, value);
    }
}

请注意,代码部分未翻译。

英文:

It seems that the binding breaks when you create the control programmatically.

Instead you can use the property changed event:

internal class CustomButton : Button
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register(
            nameof(MyProperty),
            typeof(object),
            typeof(CustomButton),
            new PropertyMetadata(null, OnMyPropertyPropertyChanged));

    private static void OnMyPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is CustomButton customButton)
        {
            customButton.Content = e.NewValue;
        }
    }

    public object MyProperty
    {
        get =&gt; GetValue(MyPropertyProperty);
        set =&gt; SetValue(MyPropertyProperty, value);
    }
}

huangapple
  • 本文由 发表于 2023年5月21日 17:21:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定