绑定到其他元素(高度减去5px)

问题描述 投票:0回答:1

以下代码是okey。

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="Window1"
    x:Name="Window1" Title="Window1" 
    Height="200" Width="300">

<Grid>
    <DockPanel LastChildFill="False">
        <Rectangle DockPanel.Dock="Top" Height="{Binding ElementName=Button1, Path=Height}"  Width="70" Fill="Yellow"></Rectangle>
        <Button x:Name="Button1" DockPanel.Dock="Bottom" Background="Red" Height="50" Width="70"/>
    </DockPanel>
</Grid>
</Window>

以下代码需要修复。

<Rectangle DockPanel.Dock="Top" Height="Button1.Height-5px"  Width="70" Fill="Yellow"></Rectangle>
c# wpf vb.net xaml binding
1个回答
0
投票

我不确定你想要获得什么,但我想要获得高度 - 5,只需使用转换器绑定。

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:younamespace"
    x:Class="Window1"
    x:Name="Window1" Title="Window1" 
    Height="200" Width="300">
<Window.Resources>
<local:RactangleHeightConverters x:Key="NameConverter"/>
</Window.Resources>   
<Grid>
    <DockPanel LastChildFill="False">
         <Rectangle DockPanel.Dock="Top" Height="{Binding ElementName=Button1, Path=Height,Converter={StaticResource NameConverter}}"  Width="70" Fill="Yellow"></Rectangle>
        <Button x:Name="Button1" DockPanel.Dock="Bottom" Background="Red" Height="50" Width="70"/>
    </DockPanel>
</Grid>
</Window>

更多信息http://www.c-sharpcorner.com/UploadFile/87b416/wpf-value-converters/

使用工具“IValueConverter”创建类

using System;  

namespace ValueConverters  
{  
    class RactangleHeightConverters:IValueConverter  
    {  
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
        {  
            return value - 5;
        }  

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
        {  
           return null;
        }  
    }  
}  
© www.soinside.com 2019 - 2024. All rights reserved.