所以我有一個 WPF 程式,其中有一個 ViewModel 和幾個視窗。我通常像這樣為我的 ViewModel 添加 DataContext:
<Window.DataContext>
<local:PrintView x:Name="printerView"/>
</Window.DataContext>
但是如果我這樣做,我會遇到創建多個 ViewModel 實體的問題,每個視窗一個實體。這意味著如果我更改一個視窗中的屬性,則另一個視窗的相同屬性不會更改。
現在我以這樣的方式完成了它,我在 App.xaml 中定義它,如下所示:
<Application.Resources>
<ResourceDictionary>
<local:PrintView x:Key="printView"/>
</ResourceDictionary>
</Application.Resources>
每個視窗中的地址如下:
DataContext="{StaticResource printView}"
但現在的問題是我想在沒有 App.Xaml 的情況下創建整個東西。有誰知道如何在沒有 App.xaml 的情況下創建相同的結果?以及沒有庫。
我正在使用 .NET Framework 4.8
編輯
我現在已經實作了@mm8 的解決方案。但是,它似乎仍然不起作用。一切都在 Xaml 部分作業,我可以訪問這些屬性。但是,后面的代碼存在問題,即當我在視窗中選擇一個值并將其保存在屬性中時:
第二個視窗
因此將選定的值保存在屬性中:
SelectedItem="{Binding selected_printer, Mode=TwoWay}"
但是我想在另一個視窗中訪問這個更改的值,無論是這樣的:
var vm = (ViewModel)this.DataContext;
vm.selected_printer
或像這樣:
ApplicationService.Instance.PrintView.selected_printer
無論我如何嘗試在另一個視窗中訪問先前更改的屬性,該屬性都不會在另一個視窗中使用新值更新。
所以這個值: SecondWindow 沒有轉移到另一個視窗,也沒有更新
我選擇的列印機定義:
private string _selected_printer;
public string selected_printer
{
get
{
return _selected_printer;
}
set
{
_selected_printer = value;
NotifyPropertyChanged(nameof(selected_printer));
}
}
我的 ViewModel 定義:
public class PrintView: INotifyPropertyChanged
我的財產改變的東西:
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
uj5u.com熱心網友回復:
您無需使用App.xaml即可創建全域資源。您可以創建自己的應用程式范圍的服務類并在那里設定您的視圖模型:
public sealed class ApplicationService
{
private ApplicationService() { }
public static ApplicationService Instance { get; } = new ApplicationService();
public PrintView PrintView { get; } = new PrintView();
}
用法:
DataContext="{Binding PrintView, Source={x:Static local:ApplicationService.Instance}}"
這基本上是視圖模型定位器的作業方式(假設PrintView實際上是一個視圖模型,盡管它的名字......)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424243.html
上一篇:系結已系結的屬性但具有標準化值
下一篇:單擊按鈕時加載框架
