2014-09-06 111 views

回答

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

+0

非常感謝!真的很簡單。 – user3952846 2014-09-06 16:36:46