나는 WPF 및 MVVM을 완전히 처음 사용하고 WPF 양식의 텍스트 상자에 속성을 연결하려고합니다. 그러나 주 개체의 두 인스턴스가 발생하여 -1 종료 오류가 발생합니다. 이것은 XAML 파일의 클래스 및 DataContext 종속성으로 인해 발생한다고 생각합니다.
왜 이것이 그럴 수 있는지에 대해 올바른 방향으로 나를 가리킬 수 있습니까?
내 XAML의 주요 부분은 다음과 같습니다.
<Window
x:Class="MyProg.MainWindowViewModel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProg"
xmlns:vm="clr-namespace:MyProg"
mc:Ignorable="d"
Title="MainWindow" Height="572" Width="855" WindowStartupLocation="CenterScreen" >
<Window.Resources>
<vm:MainWindowViewModel x:Key="viewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource ResourceKey=viewModel}">
<TextBox x:Name="textBox"
Text="{Binding FormTextBox}" />
</Grid>
</Window>
내 모델에는 다음이 포함됩니다.
namespace MyProg
{
public class MyProgModel : INotifyPropertyChanged
{
private string _textBox; // holds contents of text box
public string MyTextBox
{
get { return _textBox; }
set
{
_textBox = value;
Console.WriteLine(_textBox);
OnPropertyChanged("MyTextBox");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
Console.WriteLine("Keyboard Model OnPropertyChanged {0}", propertyName);
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
및보기 모델 :
namespace MyProg
{
public partial class MyProg : Window, INotifyPropertyChanged
{
private MyProgModel _mainWindowModel;
private string _textBox = "Pan Galactic Gargle Blaster"; // holds contents of text box
public MainWindowViewModel()
{
_mainWindowModel = new MyProgModel
{ // Instantiate and initialise _mainWindowModel
MyTextBox = "Hello from me"
};
}
public string FormTextBox
{
get { return _textBox; }
set
{
_textBox = value;
OnPropertyChanged("FormTextBox");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
Console.WriteLine("View model OnPropertyChanged {0}", propertyName);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
뷰 모델은 동시에 뷰입니다-분리하십시오. 그렇지 않으면 창 리소스에서 역 호출이 있습니다 (DataContext에 필요합니다)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다