1

我正在尝试将我的子窗口设置为我的应用程序的大小,以便它占据整个屏幕。我正在使用以下代码:

Binding widthBinding = new Binding("Width");
widthBinding.Source = App.Current.Host.Content.ActualWidth;
this.SetBinding(ChildWindow.WidthProperty, widthBinding);

Binding heightBinding = new Binding("Height");
heightBinding.Source = App.Current.Host.Content.ActualHeight;
this.SetBinding(ChildWindow.HeightProperty, heightBinding);

this子窗口在哪里。

我正在绑定它,以便当他们调整浏览器大小时,子窗口也应该如此。但是,我的子窗口没有绑定到大小。它仍然保持其默认大小。我的绑定不正确吗?

4

5 回答 5

3

我不相信你会得到约束工作。让 ChildWindow 填满屏幕的最简单方法是将 Horizo​​ntalAlignment 和 VerticalAlignment 设置为 Stretch

<controls:ChildWindow x:Class="SilverlightApplication4.ChildWindow1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
           Title="ChildWindow1"
           HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

如果您绝对想在 silverlight 中使用 ActualWidth/ActualHeight 路线,您必须执行类似...

public ChildWindow1()
{
  InitializeComponent();

  UpdateSize( null, EventArgs.Empty );

  App.Current.Host.Content.Resized += UpdateSize;
}

protected override void OnClosed( EventArgs e )
{
  App.Current.Host.Content.Resized -= UpdateSize;
}

private void UpdateSize( object sender, EventArgs e )
{
  this.Width = App.Current.Host.Content.ActualWidth;
  this.Height = App.Current.Host.Content.ActualHeight;
  this.UpdateLayout();
}
于 2012-04-04T16:28:20.057 回答
2

我认为您正在尝试绑定到ActualWidth.Width不存在的 。从绑定构造函数中删除"Width"/"Height"字符串,它应该可以工作。

Binding widthBinding = new Binding();
widthBinding.Source = App.Current.Host.Content.ActualWidth;
this.SetBinding(ChildWindow.WidthProperty, widthBinding);

Binding heightBinding = new Binding();
heightBinding.Source = App.Current.Host.Content.ActualHeight;
this.SetBinding(ChildWindow.HeightProperty, heightBinding);
于 2012-04-04T16:18:48.473 回答
1

当 ActualHeight 和 ActualWidth 发生变化时,Content 类不会引发 PropertyChanged 事件;所以 Binding 无法知道它需要刷新值。在仍然使用 Binding 的同时,有一些复杂的方法可以解决这个问题,但最简单的答案就是处理 Content.Resized 事件并自己设置值。

于 2012-04-04T16:20:41.700 回答
0

如果@Rachel 的回答不起作用,您可能想尝试这篇博文中概述的技术:

http://meleak.wordpress.com/2011/08/28/onewaytosource-binding-for-readonly-dependency-property/

根据该帖子,您不能绑定到只读属性,即 ActualWidth 和 ActualHeight 。

我不知道这是否适用于 Silverlight,但它在 WPF 中对我们来说效果很好。

于 2012-04-04T16:23:51.183 回答
0

ActualWidth 和 ActualHeight 不会在 Silverlight 中触发 PropertyChanged 事件。这是设计使然(关于优化布局引擎的性能,如果我记得的话)。因此,您永远不应该尝试绑定它们,因为它根本行不通。推荐的解决方案是处理 SizeChanged 事件,然后自己进行适当的更新。从文档中:

不要尝试将 ActualWidth 用作 ElementName 绑定的绑定源。如果您有需要基于 ActualWidth 进行更新的方案,请使用 SizeChanged 处理程序。

这是一个使用附加属性的解决方案。还应该直接将此功能包装在 XAML 友好的混合行为中(可能Behavior<FrameworkElement>)。

于 2012-04-04T16:51:39.723 回答