Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# UWP绑定到依赖项属性_C#_Uwp - Fatal编程技术网

C# UWP绑定到依赖项属性

C# UWP绑定到依赖项属性,c#,uwp,C#,Uwp,我已经使用TemplateStudio创建了一个UWP项目,我正在尝试实现一个自定义控件 这就是它看起来的样子: .xaml.cs public sealed partial class MyButton : UserControl { public MyButton() { InitializeComponent(); } public ImageSource Icon {

我已经使用TemplateStudio创建了一个UWP项目,我正在尝试实现一个自定义控件

这就是它看起来的样子:

.xaml.cs

 public sealed partial class MyButton : UserControl
    {
        public MyButton()
        {
            InitializeComponent();
        }

        public ImageSource Icon
        {
            get => (ImageSource)GetValue(s_iconProperty);
            set => SetValue(s_iconProperty, value);
        }

        public ImageSource Pointer
        {
            get => (ImageSource)GetValue(s_pointerProperty);
            set => SetValue(s_pointerProperty, value);
        }

        public static readonly DependencyProperty s_iconProperty =
          DependencyProperty.Register("Icon", typeof(ImageSource), typeof(MyButton), null);

        public static readonly DependencyProperty s_pointerProperty =
         DependencyProperty.Register("Pointer", typeof(ImageSource), typeof(MyButton), null);
    } 
.xaml

但我意识到这可能不是正确的语法

如何绑定这些依赖属性,有没有简单的方法

我已使用“添加新项”创建控件。。。用户控制

我已尝试如下设置数据绑定:

这样在用户控件的XAML中设置数据绑定是正确的。但是你没有设置装订的尺寸。如果没有数据源,绑定将无法工作。只需在用户控件中设置
Datacontext
,它就可以工作了。代码如下:

public MyButton()
{
    InitializeComponent();
    (this.Content as FrameworkElement).DataContext = this;
}

public ImageSource Icon
{
    get => (ImageSource)GetValue(s_iconProperty);
    set => SetValue(s_iconProperty, value);
}
然后可以使用用户控件设置图像源,例如:

<local:MyButton
    Width="600"
    Height="800"
    Icon="Assets/A.jpg" />

有关用户控件内部绑定的更多详细信息,请参考

我已尝试如下设置数据绑定:

这样在用户控件的XAML中设置数据绑定是正确的。但是你没有设置装订的尺寸。如果没有数据源,绑定将无法工作。只需在用户控件中设置
Datacontext
,它就可以工作了。代码如下:

public MyButton()
{
    InitializeComponent();
    (this.Content as FrameworkElement).DataContext = this;
}

public ImageSource Icon
{
    get => (ImageSource)GetValue(s_iconProperty);
    set => SetValue(s_iconProperty, value);
}
然后可以使用用户控件设置图像源,例如:

<local:MyButton
    Width="600"
    Height="800"
    Icon="Assets/A.jpg" />

有关用户控件内部绑定的更多详细信息,请参考