Wpf将两个变量绑定到Margin

时间:2014-09-06 16:02:38

标签: wpf

我有一个组件的两个不同属性,应该用于另一个组件的Margin属性。一个是左/右,另一个是上/下。是否可以将两个变量绑定到一个变量?

1 个答案:

答案 0 :(得分:0)

取决于您的情况,但需要一些转换器

1)如果您处于最简单的情况,那么"简单地说"将MultiBindingIMultiValueConverter

一起使用
<Window x:Class="MarginsBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MarginsBinding"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Slider x:Name="horizontal"
                Maximum="1000"
                DockPanel.Dock="Top"></Slider>
        <Slider x:Name="vertical"
                Maximum="1000"
                DockPanel.Dock="Top"></Slider>
        <Rectangle Fill="Red" Width="100" Height="100" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Rectangle.Margin>
                <MultiBinding>
                    <MultiBinding.Converter>
                        <local:MarginConverter></local:MarginConverter>
                    </MultiBinding.Converter>
                    <Binding ElementName="horizontal" Path="Value"></Binding>
                    <Binding ElementName="vertical" Path="Value"></Binding>
                </MultiBinding>
            </Rectangle.Margin>
        </Rectangle>
    </DockPanel>
</Window>

转换器:

using System;
using System.Windows;
using System.Windows.Data;

namespace MarginsBinding
{
    public class MarginConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Thickness margin = new Thickness
            {
                Left = (double)values[0],
                Right = (double)values[0],
                Top = (double)values[1],
                Bottom = (double)values[1]
            };

            return margin;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

2)如果您有更高级的需求,可以查看我在此处构建的另一个转换器:

control margin properties depending on another control margin properties in wpf