gpt4 book ai didi

c# - 将 Viewmodel 绑定(bind)到 View

转载 作者:行者123 更新时间:2023-12-03 10:56:11 25 4
gpt4 key购买 nike

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;

}
}

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 绑定(bind)有什么问题?
文本框什么都不显示。
公共(public)字符串名字{} - 这里的名字在调试中有值(value)。
我试过没有 Window.DataContext 并且仅适用于 文本="{绑定(bind)名字}"但没有成功。
登录绑定(bind)工作正常。

最佳答案

您需要从 中删除MainWindow.xaml 这部分:
<Window.DataContext>
<viewModels:UserViewModel />
</Window.DataContext>

因为你有两次 DataContext,
在 xaml 和 cs 中,因此不知道从哪里获取数据。

关于c# - 将 Viewmodel 绑定(bind)到 View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60072024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com