如果我定义了用户控件:
public partial class MainFooter : UserControl
{
public System.Windows.Media.Color BkColor;
}
这是 xaml:
<UserControl x:Class="Test.MainFooter">
<Grid x:Name="LayoutRoot">
<Rectangle x:Name="rctBottom_Background2"
HorizontalAlignment="Stretch"
Grid.Row="2">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.82,0.895" StartPoint="0.911,-0.442">
<GradientStop Color="{**How can I bind this to the BkColor property?}"/**>
<GradientStop Color="#00FFFFFF" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
</UserControl>
并使用:
<MyControls:MainFooter x:Name="rcrMainFooter"
BkColor="#FFE2B42A">
</MyControls:MainFooter>
如何将 Rectangle 中的 GradientStop Color 绑定(bind)到其用户控件 BkColor 属性的值?
最佳答案
当我看到这个问题提出时,答案通常是“你必须在代码中完成”,这对我来说听起来像是“Silverlight 绑定(bind)不支持这个” - 所以你必须这样做“完全手动”通过手动设置属性。但事实并非如此:
Silverlight 绑定(bind)确实支持此功能 - 只是 Silverlight XAML 不支持。
这是一个 UserControl
的示例,它基本上包装了 DataForm
。在构造函数中,您运行可以绑定(bind)到“用户控件属性”的绑定(bind)。希望如果他们将来更改对此的 XAML 支持,那么回来修复就会很简单。
App.xaml
<AddressControl MyHeader="Shipping Address"/>
AddressControl.xaml
<UserControl>
<DataForm Name="dfAddress" Header="BOUND IN CODE"/>
</UserControl>
可选:表示您已使用注释绑定(bind)代码中的值
AddressControl.xaml.cs
publicAddressControl()
{
InitializeComponent();
// bind the HeaderProperty of 'dfAddress' to the 'MyHeader' dependency
// property defined in this file
dfAddress.SetBinding(DataForm.HeaderProperty,
new System.Windows.Data.Binding { Source = this,
Path = new PropertyPath("MyHeader") });
}
// standard string dependency property
public string MyHeader
{
get { return (string)GetValue(MyHeaderProperty); }
set { SetValue(MyHeaderProperty, value); }
}
public static readonly DependencyProperty MyHeaderProperty =
DependencyProperty.Register("MyHeader", typeof(string),
typeof(AddressControl), null);
这会将我的 AddressControl
用户控件上的 MyHeader
属性绑定(bind)到数据表单上的 Header
属性。我将其设为“我的”只是为了便于阅读 - 但实际上我在实际代码中仅使用“标题”。
真遗憾,我们仍然无法在 XAML 中执行此操作,但它比我第一次 try catch DataContextChanged
事件然后手动设置内容要好。
关于.net - Silverlight:将子控件属性绑定(bind)到用户控件中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/421581/