窗口高度和宽度绑定:只从DataContext中获取一个

时间:2015-02-21 18:49:04

标签: c# wpf xaml binding

我一直在谷歌搜索这个没有得到这个问题:

简单的xaml:

<Window x:Class="WpfHeightBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHeightBinding="clr-namespace:WpfHeightBinding"
        Title="MainWindow" 
        Width="{Binding Width}"
        Height="{Binding Height}"
        SizeToContent="Manual"
        >
    <Window.DataContext>
        <wpfHeightBinding:TheDataContext />
    </Window.DataContext>
    <Grid>
    </Grid>
</Window>

我将Width和Height绑定到数据上下文。这是cs代码

using System.Windows;

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

    public class TheDataContext
    {
        public int Width
        {
            get { return 200; }
        }

        public int Height
        {
            get { return 400; }
        }
    }
}

我为两个吸气剂设置了断点。仅提取第一个,忽略Height。如果我在xaml中切换HeightWidth,则仅提取Height并忽略Width

我真的无法解释这种行为。窗户的高度似乎是任意的。我没有MinHeight,没有其他任何影响它,绑定会发生什么?没有错误。 SizeToContent无效。

我会理解,如果没有使用它们,因为在DataContext初始化之前可能已经提取了它们,但查询了DataContext

1 个答案:

答案 0 :(得分:2)

你需要在代码隐藏中给你的'宽度'和'高度'属性设置器 - 然后让你的绑定'TwoWay':

XAML

<Window x:Class="WpfHeightBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHeightBinding="clr-namespace:WpfHeightBinding"
    Title="MainWindow" 
    Width="{Binding Width, Mode=TwoWay}"
    Height="{Binding Height, Mode=TwoWay}"
    SizeToContent="Manual"        
    >
<Window.DataContext>
    <wpfHeightBinding:TheDataContext />
</Window.DataContext>

代码隐藏:

public class TheDataContext
{
    public int Width { get { return 800; } set { } }
    public int Height { get { return 200; } set { } }
}