C# UWP绑定到依赖项属性
我已经使用TemplateStudio创建了一个UWP项目,我正在尝试实现一个自定义控件 这就是它看起来的样子: .xaml.csC# UWP绑定到依赖项属性,c#,uwp,C#,Uwp,我已经使用TemplateStudio创建了一个UWP项目,我正在尝试实现一个自定义控件 这就是它看起来的样子: .xaml.cs public sealed partial class MyButton : UserControl { public MyButton() { InitializeComponent(); } public ImageSource Icon {
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" />
有关用户控件内部绑定的更多详细信息,请参考