在我的XAML中,我正在执行以下操作
<Label Content="{Binding ElementName=Root, Path=UserData.Email, Mode=OneWay}" />
该Root
元素是我Window
自己和UserData
是一个get; private set;
在我隐藏文件自动财产,该Email
财产是获得仅是类型string
。
UserData
用户登录后将设置该对象。但是绑定没有从该对象获取值。我已验证该对象确实包含正确的数据,但不是null
。我在这里想念什么?
我继续为此创建了一个hello世界版本。这是xml。单击按钮将其更改为文本框中的文本时,只需更改横幅。我找不到一个超级简单的例子,所以我举了一个例子。显然,有一些更高级的方法可以做到这一点,但是它应该可以作为一个简单的版本。
<Window x:Class="Hello_World.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Name="MyLabel" Content="{Binding MyLabel}" HorizontalAlignment="Left" Margin="58,37,0,0" VerticalAlignment="Top" Height="65" Width="423" FontSize="44"/>
<TextBox Name="MyTextBox" HorizontalAlignment="Left" Height="28" Margin="163,162,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="163"/>
<Button Content="Change Banner" HorizontalAlignment="Left" Margin="251,209,0,0" VerticalAlignment="Top" Width="109" Click="Button_Click"/>
</Grid>
</Window>
接下来是实现INotifyPropertyChanged
接口的ModelView 。请注意,您的属性必须是具有getter,setter和backing字段的公共属性。这样,OnPropetyChanged()
只要设置了属性,就可以调用该方法。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hello_World
{
public class MainViewModel: INotifyPropertyChanged
{
private string _myLabel;
public string MyLabel
{
get { return _myLabel; }
set
{
_myLabel = value;
OnPropertyChanged(nameof(MyLabel));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propetyName)
{
if(PropertyChanged != null)
PropertyChanged(this,new PropertyChangedEventArgs(propetyName));
}
}
}
最后是MainWindow。设置DataContext
在主构造函数。请注意,我可以设置DataContext
主网格的,所有子网格都将继承相同的网格DataContext
。这将使您不必单独设置所有组件。
namespace Hello_World
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private MainViewModel MyViewModel;
public MainWindow()
{
InitializeComponent();
MyViewModel = new MainViewModel();
// Here's where I'm setting the object to look at.
DataContext = MyViewModel;
// Now I don't need to access the textbox directly.
MyViewModel.MyLabel = "Hello World";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: ICommand is a more advanced topic.
MyViewModel.MyLabel = MyTextBox.Text;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句