【问题标题】:Custom Control Dependency Property Binding to Property自定义控件依赖属性绑定到属性
【发布时间】:2012-08-29 07:17:19
【问题描述】:

只是玩弄不同类型的绑定,并让一个属性将我的自定义控件的依赖属性绑定到另一个属性。

XAML:

<UserControl x:Class="BrickBreaker.Brick"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="20" d:DesignWidth="50"  >
<Rectangle Width="50" Height="20" RadiusX="3" RadiusY="3" Stroke="Black" Fill="{Binding BrickFill, Mode=TwoWay}" />

代码背后:

public partial class Brick : UserControl
{
    public Brick()
    {
        InitializeComponent();

    }

    public Brush BrickFill
    {
        get { return (Brush)GetValue(BrickFillProperty); }
        set { SetValue(BrickFillProperty, value); }
    }

    // Using a DependencyProperty as the backing store for BrickFill.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BrickFillProperty =
        DependencyProperty.Register("BrickFill", typeof(Brush), typeof(Brick), null);



}

MainWindow.xaml 中的实现

<UserControl x:Class="BrickBreaker.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:BrickBreaker="clr-namespace:BrickBreaker" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">
    <BrickBreaker:Brick Margin="100,100,0,0" BrickFill="Azure"/>
</Grid>

基本上我想在后面的代码中将 Rectangles Fill 属性绑定到 Dependency 属性。

谢谢。

史蒂夫

【问题讨论】:

    标签: c# wpf silverlight custom-controls dependency-properties


    【解决方案1】:

    具体的问题是什么?将 UserControl 的 DataContext 设置为代码隐藏,如:

    <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
    
    </UserControl>
    

    【讨论】:

      【解决方案2】:

      缺少这个:DataContext="{Binding RelativeSource={RelativeSource Self}}"

      【讨论】:

        猜你喜欢
        • 2012-08-07
        • 2019-05-26
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        • 2013-10-16
        相关资源
        最近更新 更多