通过添加一些值绑定到Canvas.TopProperty

时间:2015-04-06 08:28:36

标签: c# wpf xaml binding

我有这段代码:

<Rectangle x:Name="cage" Height="247" Canvas.Left="278" Canvas.Top="220" Width="450">
        <Rectangle.Fill>
            <ImageBrush Stretch="None" ImageSource="resources/cage.gif"/>
        </Rectangle.Fill>
    </Rectangle>

<Label x:Name="to1" Content="1" Canvas.Left="550" Canvas.Top="{Binding Source=cage, Path=Canvas.Top, Mode=OneWay}"  BorderBrush="#FF272727" BorderThickness="1" Height="38" Width="38" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="20" PreviewMouseDown="to1_PreviewMouseDown"/>

绑定正在运行,但我希望保持此元素相对于彼此的位置。换句话说,如果我移动笼子,topproperty的标签变成了“移动值+ 285”。怎么做?

2 个答案:

答案 0 :(得分:0)

考虑使用转换器作为位建议。

一个简单的例子应如下所示:

<强> XAML

<UserControl.Resources>
    <converterNamespace:LabelOffsetConverter x:Key="labelOffsetConverter"/>
</UserControl.Resources>

<Label x:Name="to1" Content="1" Canvas.Left="550" 
       Canvas.Top="{Binding Source=cage, Path=Canvas.Top, Mode=OneWay,
                    Converter={StaticResource labelOffsetConverter}"
       BorderBrush="#FF272727" 
       BorderThickness="1" 
       Height="38" Width="38" 
       HorizontalContentAlignment="Center" 
       VerticalContentAlignment="Center" 
       FontSize="20" PreviewMouseDown="to1_PreviewMouseDown"/>

转换代码

public class LabelOffsetConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is double))
            return DependencyProperty.UnsetValue;

        double doubleValue = (double)value;
        return doubleValue + 285;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // No need to implement, since the binding is in one way mode.
        throw new NotImplementedException();
    }
}

答案 1 :(得分:0)

通过这种方式解决: 的 C#

public class Label1offset : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is double))
                return DependencyProperty.UnsetValue;

double doubleValue = (double)value; return doubleValue + 65.0; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // No need to implement, since the binding is in one way mode. throw new NotImplementedException(); } } Binding binding1 = new Binding(); binding1.Converter = new Label1offset(); binding1.Source = cage; binding1.Path = new PropertyPath(Canvas.TopProperty); binding1.Mode = BindingMode.OneWay; to1.SetBinding(Canvas.TopProperty, binding1);