我试图展现在我的WPF applike这样一个网格2所画布控制。 该将是一样 但它不能这样做,因为margin属性不能被用作变量。 所以,我想“ 厚度 ”。 但我不能转换的厚度变化,因为它是一个double类型。 那么,有没有变通解决办法呢?
Answer 1:
你可以写一个专门的值转换器:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
namespace WpfMagic
{
class EditableMarginConverter : IValueConverter
{
private double GetMarginPartValue(Thickness margin, string defaultValue, IDictionary<string, string> instructions)
{
string sourceValue;
string value = instructions.TryGetValue(defaultValue, out sourceValue) ? sourceValue : defaultValue;
double numericalValue;
if (double.TryParse(value, out numericalValue))
{
return numericalValue;
}
return value == "left" ? margin.Left :
value == "top" ? margin.Top :
value == "right" ? margin.Right :
margin.Bottom;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Thickness inputMargin = (Thickness)value;
IDictionary<string, string> instructions = (parameter as string).Split()
.Select(s => s.Split('='))
.ToDictionary(t => t[0].ToLowerInvariant(), t => t[1].ToLowerInvariant());
Thickness outputMargin = new Thickness
{
Left = GetMarginPartValue(inputMargin, "left", instructions),
Top = GetMarginPartValue(inputMargin, "top", instructions),
Right = GetMarginPartValue(inputMargin, "right", instructions),
Bottom = GetMarginPartValue(inputMargin, "bottom", instructions)
};
return outputMargin;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
你会使用这样的:
<StackPanel xmlns:local="clr-namespace:WpfMagic" Orientation="Horizontal">
<StackPanel.Resources>
<local:EditableMarginConverter x:Key="marginConverter"></local:EditableMarginConverter>
</StackPanel.Resources>
<Canvas x:Name="first_canvas"
Width="100"
Height="100"
Margin="0 0 10 0"
Background="Red">
</Canvas>
<Canvas x:Name="second_canvas"
Width="100"
Height="100"
Background="Green"
Margin="{Binding Margin,
ElementName=first_canvas,
Converter={StaticResource marginConverter},
ConverterParameter='Left=Right Right=0'}">
</Canvas>
</StackPanel>
这样做的这是一个可重用的方式,但如果它是一次性的,你可能应该使用一些程序上的管道,除非你是教条,并希望有完美的XAML。
Answer 2:
我实现它只是这样...
int right = system.convert.ToInt32(first_canvas.margin.right)
second_canvas.margin = new thickness(left = right)
文章来源: control margin properties depending on another control margin properties in wpf