[英]Change UserControl property using XAML
我有我的UserControl
<UserControl x:Class="CustomCtrl.MyButton">
<Button x:Name="Btn" />
</UserControl>
我在Window
使用UserControl
<Window>
<Grid>
<MyButton Background="Aqua" />
</Grid>
</Window>
我想改变Background
的按钮的属性Btn
使用属性Background
我的UserControl
与XAML。
我尝试添加Background
属性
public class MyButton: UserControl
{
public new Brush Background
{
get
{ return Btn.GetValue(BackgroundProperty) as Brush; }
set
{ Btn.SetValue(BackgroundProperty, value); }
}
}
但这没有效果。
相反,如果我使用代码MyButtonControl.Background = Brushes.Aqua;
, 有用。
为什么? 我该如何解决这个问题?
该UserControl.Background
取 , UserControls
不自定义控件,你必须在此属性为如何使用没有控制权。 如果只想更改一个控件的背景,则可以公开一个新的依赖项属性,并将其绑定到Button.Background
。
在我看来,您有两种选择:
简单的方法是,只需将“ Btn”背景设置为“透明”,如下所示:
<UserControl x:Class="CustomCtrl.MyButton"> <Button x:Name="Btn" Background="Transparent"/> </UserControl>
另一种方法是将按钮的背景色绑定到控件的背景色:
<UserControl x:Class="CustomCtrl.MyButton" x:Name="control"> <Button x:Name="Btn" Background="{Binding Background, ElementName=control}"/> </UserControl>
两者都经过测试,似乎可以正常工作。
同
<Window>
<Grid>
<MyButton Background="Aqua" />
</Grid>
</Window>
您正在设置UserControl
的背景色。 要设置Button
的背景色,您必须
<UserControl x:Class="CustomCtrl.MyButton">
<Button x:Name="Btn" Background="Aqua" />
</UserControl>
编辑(在OP注释之后):您不能修改UserControl.Background
,但是可以使用新属性:
public Brush ButtonBackground {
get {
return this.Btn.Background;
}
set {
this.Btn.Background = value;
}
}
接着:
<Window>
<Grid>
<MyButton ButtonBackground="Aqua" />
</Grid>
</Window>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.