我正试图在MVVM之后的解决方案中创建两个WPF项目和一个DLL项目。
第一个WPF将用作第二个WPF的管理面板(例如:您编写文本,按下按钮,文本将显示在第二个"WPF窗口"中)。
我想把我的模型放在DLL中。
我的问题是我不知道如何在第二个WPF中显示文本(notify?)。
我在视图模型中实现了INotifyPropertyChanged
。
然后我被卡住了,我不知道该怎么办…
我的解决方案如下:
WPF_Solution
- 显示WPF
- 主窗口.xaml
- Dll_mvm
- 文本.cs:
- 管理WPF
- DisplayViewModel.cs
- 主窗口.xaml
显示和管理都引用DLL。
文本.cs:
public class Text
{
string _textToDisplay;
/// <summary>
/// Text to display on screen
/// </summary>
public string TextToDisplay
{
get { return _textToDisplay; }
set { _textToDisplay = value; }
}
}
DisplayViewModel.cs:
public class DisplayViewModel : INotifyPropertyChanged
{
private Text _text;
/// <summary>
/// Constructs the default instance of a ToDisplayViewModel
/// </summary>
public DisplayViewModel()
{
_text = new Text();
}
/// <summary>
/// Accessors
/// </summary>
public Text Text
{
get { return _text; }
set { _text = value; }
}
public string TextToDisplay
{
get { return Text.TextToDisplay; }
set
{
if (Text.TextToDisplay != value)
{
Text.TextToDisplay = value;
RaisePropertyChanged("TextToDisplay");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
管理面板:
public partial class MainWindow : Window
{
private DisplayViewModel _displayThings;
private Affichage.MainWindow _displayer = new Affichage.MainWindow();
public MainWindow()
{
InitializeComponent();
_displayThings = (DisplayViewModel)base.DataContext;
_displayer.Show();
}
private void disp_btn_Click(object sender, RoutedEventArgs e)
{
_displayThings.TextToDisplay = textBox.Text;
}
}
WPF只是Control窗口中的一个按钮和一个文本框,以及Display窗口中的文本框。链接到视图模型
<Window.DataContext>
<!-- Declaratively create an instance of DisplayViewModel -->
<local:DisplayViewModel />
</Window.DataContext>
TextBox与Text="{Binding TextToDisplay}
"绑定
我的Viewmodel也应该在DLL中共享吗?
如何通知其他项目模型发生了更改?
删除以下标记,因为它将创建DisplayViewModel类的新实例:
<Window.DataContext>
<!-- Declaratively create an instance of DisplayViewModel -->
<local:DisplayViewModel />
</Window.DataContext>
并将子窗口的DataContext属性分配给DisplayViewModel类的实例,您实际上正在设置的TextToDisplay属性为:
public partial class MainWindow : Window
{
private DisplayViewModel _displayThings = = new DisplayViewModel();
private Affichage.MainWindow _displayer = new Affichage.MainWindow();
public MainWindow()
{
InitializeComponent();
_displayer.DataContext = _displayThings;
_displayer.Show();
}
private void disp_btn_Click(object sender, RoutedEventArgs e)
{
_displayThings.TextToDisplay = textBox.Text;
}
}