你真正想要做的就是使用MVVM模式將你的邏輯從你的視圖中分離出來。這樣,你可以將你的ViewModel傳遞給操作子窗口的東西,而不是子窗口本身。
例如,對於子畫面的基本視圖模型可能是:
public class ChildWindowViewModel: INotifyPropertyChanged {
private string _title;
public string Title{
get { return _title; }
set{if (value != _title){
_title = value;
OnPropertyChanged("Title");
}}
}
private void OnPropertyChanged(string propertyName){
var handle = PropertyChanged;
if (handle != null){
handle(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
然後您設置的DataContext的視圖模型在創建子窗口是這樣的:
//Creating the child window
ChildWindow child = new ChildWindow();
ChildWindowViewModel childViewModel = new ChildWindowViewModel();
child.DataContext = childViewModel;
//do stuff with child...
和鉤子窗口標題直到Xaml中的ViewModel是這樣的:
<Namespace:ChildWindow
x:Class="Namespace.MyClass">
<Namespace:ChildWindow.Title>
<TextBlock Width="300" TextTrimming="WordEllipsis" Text="{Binding Path=Title}/>
</Namespace:ChildWindow.Title>
</Namespace:Childwindow>
然後,當你要更改標題,您可以使用
childViewModel.Title = "A Very Long Title That Will Be Cut Short In Its Prime";
在視圖模型設置標題將觸發PropertyChanged事件,這將導致XAML視圖本身與新設置的值更新。這可能看起來像是一個非常漫長的做事方式,但如果你想一下這可以讓你做幾分鐘,你會看到一些巨大的好處。綁定超出了簡單的標題文本...
希望這將所有的工作,但我從記憶中這樣對不起,因爲任何錯誤...