将画布宽度/高度绑定到自定义静态属性?

时间:2013-11-10 19:42:49

标签: c# xaml windows-8.1

我正在尝试将我的画布大小设置为我在App.xaml.cs文件中定义如下的静态属性类的特定宽度/高度:

public class CanvasAttr
{
    public static double Width 
    { 
        get 
        {
            return Window.Current.Bounds.Width / 4;    
        } 
    }
    public static double Height 
    { 
        get 
        {
            return Window.Current.Bounds.Height / 4;    
        } 
    }
}

这是我的MainPage.xaml

<Page
    x:Class="Bossanova.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Bossanova"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Height="765.015">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.Resources>
            <Style x:Key="DrawSurface" TargetType="Canvas">
                <Setter Property="Width" Value="{Binding CanvasAttr.Width}" />
                <Setter Property="Height" Value="{Binding CanvasAttr.Height}" />
                <Setter Property="Background" Value="AliceBlue" />
            </Style>
        </Grid.Resources>
        <Canvas x:Name="Main" Style="{StaticResource DrawSurface}">

        </Canvas>
    </Grid>
</Page>

如您所见,在<Style>定义中,我为画布的“宽度”和“高度”属性添加了<Setter>个标签。问题是简单的{Binding CanvasAttr.Width}似乎不会影响任何事情。我需要做些什么才能做到这一点?

2 个答案:

答案 0 :(得分:2)

使用x:Static绑定到XAML中的静态属性 -

<Setter Property="Width" Value="{x:Static local:CanvasAttr.Width}" />
<Setter Property="Height" Value="{x:Static local:CanvasAttr.Height}" />

答案 1 :(得分:0)

不需要那种约束力。只需创建一个合适的网格布局:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="3*"/>
    </Grid.RowDefinitions>
    <Canvas x:Name="Main" Background="AliceBlue">

    </Canvas>
</Grid>

但请注意,Canvas仅对其子元素进行绝对定位。因此,设置画布的宽度或高度对其子画面没有太大影响。