由XAML创建的控件的绑定工作正常,但由代码创建的控件的绑定不起作用

ibps3vxo  于 2023-05-27  发布在  其他
关注(0)|答案(1)|浏览(130)
// 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";
        }
    }
}

当你运行上面的代码时,只有null值,也就是第一次绑定时的值,会被加载,之后不会被更新。
但是,如果您注解掉mainWindow.Content = new CustomButton();并取消注解<!--<ex:CustomButton/>-->以在xaml中而不是在代码中创建它,则绑定将正常工作。
我尝试在Loaded事件中设置绑定,因为我认为它可能与初始化有关,但结果是一样的。
为什么绑定失败?
我正在尝试创建可继承的页面或自定义控件,因此我正在尝试从代码创建控件和绑定,而不使用xaml。

tvmytwxo

tvmytwxo1#

当您以编程方式创建控件时,绑定似乎会中断。
相反,您可以使用属性更改事件:

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);
    }
}

相关问题