C# 窗口高度和宽度绑定:仅从DataContext获取一个
我一直在谷歌上搜索这个,但没有得到这个问题: 简单xaml:C# 窗口高度和宽度绑定:仅从DataContext获取一个,c#,wpf,xaml,binding,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:Wpf
<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>
我为两个getter设置了断点。只提取第一个,忽略高度。如果在xaml中切换Height
和Width
,则仅获取Height
,而忽略Width
我真的无法解释这种行为。窗户的高度似乎是任意的。我没有MinHeight
,没有其他影响,绑定会发生什么?没有错误<代码>大小内容无效
如果在初始化
DataContext
之前没有使用它们,那么我会理解,但是DataContext
会被查询。您需要在代码隐藏中提供“宽度”和“高度”属性设置器,然后使绑定“双向”:
XAML
请检查此链接是否有帮助。一种可能的替代方法可能是使用
OneTime
绑定。。。我不确定,我从未测试过。
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; }
}
}
}
<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 { } }
}