WPF将属性的值设置为另一个属性的值的比率

时间:2016-02-04 20:04:10

标签: c# wpf xaml binding

我想知道如果在XAML中没有触及视图模型,我可以做thisthis之类的事情,除非使用其他属性的比例。

我有一个内部有2个椭圆的按钮控件,我希望其中一个椭圆的边距根据另一个的高度而变化。

类似于:

<Ellipse Margin=.2*"{Binding ElementName=OtherEllipse, Path=Height}"/>

2 个答案:

答案 0 :(得分:0)

您可以,您需要编写自定义IValueConverter。 http://www.codeproject.com/Tips/868163/IValueConverter-Example-and-Usage-in-WPF

如果您需要传递参数:Passing values to IValueConverter

答案 1 :(得分:0)

MainWindow.xaml

<Window x:Class="MultiBindingConverterDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MultiBindingConverterDemo"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800">
<StackPanel>
    <StackPanel.Resources>
        <local:MultiplyValueConverter x:Key="MultiplyValueConverter"/>
    </StackPanel.Resources>
    <Ellipse x:Name="OtherEllipse" Width="100" Height="50" Fill="Red"/>
    <Ellipse Width="50" Height="50" Fill="Blue" 
             Margin="{Binding Path=Height, 
                              ElementName=OtherEllipse, 
                              Converter={StaticResource MultiplyValueConverter}, 
                              ConverterParameter=0.2}">
    </Ellipse>
</StackPanel>

MainWindow.xaml.cs

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

namespace MultiBindingConverterDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MultiplyValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double height = (double)value;
            double multiplier = double.Parse((string)parameter);
            return new Thickness(height * multiplier);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}