gpt4 book ai didi

c# - 绑定(bind)用户控件值并添加填充

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:29 29 4
gpt4 key购买 nike

我有两个问题。

1:我用第二个矩形的大小限制了第一个矩形。如何为矩形的大小添加额外的填充?例如

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

这将适用于 width 和 height 属性。所以矩形与前一个矩形接壤。

2:公开颜色属性“绿色”,这样我就可以更改我为该用户控件创建的每个实例的颜色。

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>

最佳答案

您可以将转换器添加到高亮矩形的 HeightWidth 绑定(bind):

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>

像这样将它添加到您的绑定(bind)中:

<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 绑定(bind)到一个属性。如果您希望 UserControl 的使用者能够绑定(bind)到颜色,请将其作为“DependencyProperty”添加到 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 属性绑定(bind)到这个 DependencyProperty

关于c# - 绑定(bind)用户控件值并添加填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292361/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com