绑定用户控件值并添加填充

时间:2015-12-15 14:56:08

标签: c# wpf

我有两个问题。

1:我将第二个矩形的大小绑定到第一个矩形。如何在矩形的大小中添加额外的填充?例如

Width="{Binding Path=Height + 5,...

这适用于width和height属性。因此矩形与前一个矩形相邻。

2:将color属性公开为'green',这样我就可以更改我为此用户控件创建的每个实例的颜色。

enter image description here

<UserControl x:Class="WpfApplication1.VNode"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Canvas VerticalAlignment="Center" HorizontalAlignment="Center">
        <Rectangle Name="Base" Fill="Green" Width="50" Height="50"/>
        <Rectangle Name="Highlight"  
                   Height="{Binding Path=Width, ElementName=Base, UpdateSourceTrigger=PropertyChanged}"
                   Width="{Binding Path=Height, ElementName=Base, UpdateSourceTrigger=PropertyChanged}" 
                   Fill="Transparent"
                   Stroke="White"
                   StrokeThickness="2">
        </Rectangle>
    </Canvas>
</UserControl>

1 个答案:

答案 0 :(得分:3)

您可以将转换器添加到突出显示矩形的HeightWidth绑定中:

public class AddHeightConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (double)value + 5.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return System.Windows.Data.Binding.DoNothing;
    }
}

您在XAML中引用如此(假设您已声明名为local的命名空间):

<UserControl.Resources>
    <local:AddHeightConverter x:Key="AddHeightConverter" />
</UserControl.Resources>

将其添加到您的绑定中,如下所示:

<Canvas VerticalAlignment="Center" HorizontalAlignment="Center">
    <Rectangle Name="Base" Fill="Green" Width="50" Height="50"/>
    <Rectangle Name="Highlight"  
               Height="{Binding Path=Width, Converter={StaticResource AddHeightConverter}, ElementName=Base, UpdateSourceTrigger=PropertyChanged}"
               Width="{Binding Path=Height, Converter={StaticResource AddHeightConverter}, ElementName=Base, UpdateSourceTrigger=PropertyChanged}" 
               Fill="Transparent"
               Stroke="White"
               StrokeThickness="2">
    </Rectangle>
</Canvas>

您可以将第一个矩形Fill绑定到属性。如果您希望UserControl的使用者能够绑定到颜色,请将其添加为“DependencyProperty”&#39;到UserControl:

public static readonly DependencyProperty FillProperty = DependencyProperty.Register("Fill",    typeof(Brush), typeof(VNode), new PropertyMetadata(Brushes.Green));    

public Brush Fill
{
    get { return (Brush)GetValue(FillProperty); }
    set { SetValue(FillProperty, value); }
}

然后将Rectangle的Fill属性绑定到此DependencyProperty