1

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

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 属性。

谢谢。

史蒂夫

4

2 回答 2

1

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

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

</UserControl>
于 2012-09-04T15:37:50.403 回答
0

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

于 2012-09-05T06:05:00.383 回答