在WPF中相对指定弹出窗口大小

时间:2014-10-14 07:01:31

标签: c# wpf

在WPF中,我有以下Popup小键盘。它显示在mainDisplay的中心,大小固定。

<Popup PlacementTarget="{Binding ElementName=mainDisplay}" Placement="Center" Name="numpadPop">
    <Frame Width="300" Height="300" Name="numpadFrame">
    </Frame>
</Popup>

有没有办法相对指定它的大小,比如说mainDisplay的高度的80%?谢谢!


编辑:在尝试Kenny的解决方案时,我在XAML中遇到错误。以下是我的App.xaml

<Application x:Class="myappname.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:myappname"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <local:MySizeConverter x:Key="sizeConverter"/>    
    </Application.Resources>
</Application>

错误:(我确实定义了MySizeConverter类)

Error   1   The property "Resources" can only be set once.
Error   2   The namespace prefix "local" is not defined.
Error   14  The name "MySizeConverter" does not exist in the namespace "clr-namespace:myappname".
Error   6   The "Key" attribute can only be used on an element that is contained in "IDictionary".

更新: 最初MySizeConverter不是public,这似乎是导致此问题的原因。

1 个答案:

答案 0 :(得分:2)

您可以将框架的高度绑定到mainDisplay的高度,还需要指定一个converter,它接受​​mainDisplay的高度并返回框架的高度。< / p>

<Frame Height="{Binding ElementName=mainDisplay, Path=ActualHeight, Converter={StaticResource sizeConverter}}" Width="{Binding ElementName=mainDisplay, Path=ActualWidth, Converter={StaticResource sizeConverter}}" Name="numpadFrame">
</Frame>

转换器:

public class sizeConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return 0.8 * (double)value;
    }

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

将其添加到App的资源字典(App.xaml),以便您可以使用{StaticResource key}引用它。

<Application x:Class="yournamespace.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:yournamespace"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <local:sizeConverter x:Key="sizeConverter" />
    </Application.Resources>
</Application>

如果您在编译代码和XAML时遇到问题,请阅读tutorial

相关问题