2
我有一個MainView窗口,其寬度和高度我試圖從其代碼隱藏類綁定。當綁定到MainView窗口的寬度屬性時綁定錯誤
<Window x:Class="RpP25.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shared="http://schemas.actiprosoftware.com/winfx/xaml/shared"
xmlns:docking="http://schemas.actiprosoftware.com/winfx/xaml/docking"
xmlns:themes="http://schemas.actiprosoftware.com/winfx/xaml/themes"
xmlns:RpWin="clr-namespace:RpP25"
xmlns:RpWinCmds="clr-namespace:RpP25.Commands"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="{Binding Path=FileName, Converter={StaticResource WindowTitleNameConverter}}"
Height="{Binding Path=WindowHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
Width="{Binding Path=WindowWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
Icon="images/CobWhite.ico"
Loaded="Window_Loaded"
Closing="Window_Closing">
後面的代碼具有屬性,並通過ViewModel MainVM設置datacontext。
public partial class MainView : Window, INotifyPropertyChanged
{
// Constant Fields
private const double windowDefaultWidth_ = 720;
private const double windowDefaultHeight_ = 400;
// Private Fields
private RegistryKey RegKey_; // Registry Key to hold Registry Subkey
private WindowState windowState_ = WindowState.Normal; // Display State of the MainWindow (Min,Max or Normal)
private double windowWidth_ = windowDefaultWidth_; // Width of the MainWindow
private double windowHeight_ = windowDefaultHeight_; // Height of the MainWindow
#region Constructors
public MainView()
{
InitializeComponent();
DataContext = new MainVM();
// Get the state of the window and the width/height from the registry
ReadRegistryValues();
/// <summary>
/// Gets the Width of the Window
/// </summary>
public double WindowWidth
{
get { return windowWidth_; }
set { windowWidth_ = value; NotifyPropertyChanged("WindowWidth"); }
}
/// <summary>
/// Gets the Height of the Window
/// </summary>
public double WindowHeight
{
get { return windowHeight_; }
set { windowHeight_ = value; NotifyPropertyChanged("windowHeight"); }
}
...
}
此窗口創建自App::OnStartup()
。
當我運行代碼時,調試器會在輸出窗口中引發以下錯誤。
找不到與參考'RelativeSource FindAncestor,AncestorType ='System.Windows.Window',AncestorLevel ='1'綁定的源代碼。 BindingExpression:路徑= WINDOWHEIGHT;的DataItem = NULL;目標元素是'MainView'(Name ='');目標屬性是'高度'(類型'Double')
和類似的WindowWidth
。
我想我理解結合模式,但我想我錯了:(
我的想法是使用FindAncestor尋找一個窗口會導致它來查找視覺樹,直到它找到的MainView窗口對是我的特性。
任何幫助將非常感激。
感謝 - 工作! – Pat 2012-01-14 04:55:52