【发布时间】:2020-02-05 08:48:42
【问题描述】:
MainWindow.xaml
<Window x:Class="SDT.MainWindow"
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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
xmlns:viewModels="clr-namespace:SDT.ViewModels"
Height="500" Width="700" WindowStyle="None" AllowsTransparency="False" ResizeMode="NoResize" Background="#FF2C2C2C"
TextElement.Foreground="{DynamicResource MaterialDesignBody}" TextElement.FontWeight="SemiBold">
<Window.DataContext>
<viewModels:UserViewModel />
</Window.DataContext>
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="308,90,0,0" TextWrapping="Wrap" Text = "{Binding Login}" VerticalAlignment="Top" Width="120"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="152,200,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<Button Content="Submit" Command="{Binding SubmitLoginDataCommand}" HorizontalAlignment="Left" Margin="567,259,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
MainWindows.cs
public partial class MainWindow : Window
{
UserViewModel userViewModel = new UserViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = userViewModel;
}
}
用户视图模型
public class UserViewModel : INotifyPropertyChanged
{
private UserService userService = new UserService();
public string _firstName;
public string Login { get; set; }
public void SubmitLoginData(object loginData)
{
userService.CheckUserExist(Login);
}
public ICommand SubmitLoginDataCommand => new RelayCommand(SubmitLoginData, param => true);
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName != value)
{
_firstName = value;
OnPropertyChanged("FirstName");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
你好。 FirstName 绑定有什么问题? 文本框什么都不显示。 public string FirstName{} - 这里的 FirstName 在调试中具有价值。 我尝试不使用 Window.DataContext 并且仅使用 Text="{Binding FirstName}" 但没有成功。 登录绑定工作正常。
【问题讨论】:
-
我曾经遇到过类似的问题,是由隐形字符引起的。如果您注释掉/删除有问题的行,复制登录绑定的行并将绑定从“登录”更改为“名字”,您是否仍然遇到同样的问题?
-
顺便说一句,如果你使用
OnPropertyChanged(nameof(FirstName))而不是硬编码属性名,你的代码会更不容易出错。 -
@Frauke 很遗憾,没有变化
-
尝试初始化userviewmodel的构造函数中的属性,并从后面的代码中删除数据上下文代码。
标签: c# mvvm data-binding