【发布时间】:2019-01-03 22:43:44
【问题描述】:
我有一个带有文本块和按钮的简单页面。我想在按下按钮时更改文本。但是使用 Page 的 Data.Name 属性中的文本。
我知道我可以有这个更简单的(只有 Name 而不是 Data.Name),但我需要 Data.Name,不要问为什么。
为此,我有一个 DataType 类,它具有该类的 Name 属性和名为 Data 的对象。我想在此页面中包含数据,并将文本绑定到 Data.Name 属性。
当我点击按钮时,什么也没有发生,问题是我怎样才能做到这一点?
XAML:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Data.Name, Mode=OneWay}"/>
<Button Grid.Row="1" Content="Change" Click="Button_Click"/>
</Grid>
</Page>
类数据类型
public ref class DataType: public INotifyPropertyChanged {
public:
property String^ Name
{
String^ get() {
return m_Name;
}
void set(String^ value) {
m_Name = value;
OnPropertyChanged("Name");
}
}
virtual event PropertyChangedEventHandler^ PropertyChanged;
private:
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
}
String^ m_Name;
};
类MainPage
public ref class MainPage sealed: public INotifyPropertyChanged
{
public:
MainPage();
property DataType^ Data {
DataType^ get() {
return m_Data;
}
void set(DataType^ value) {
m_Data = value;
OnPropertyChanged("Data");
}
}
virtual event PropertyChangedEventHandler^ PropertyChanged;
private:
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
}
void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
Data->Name = rand() & 1 ? "Test1" : "Test2";
OnPropertyChanged("Data");
}
DataType^ m_Data;
};
【问题讨论】:
-
你试过
x:Bind吗? -
您需要将页面的DataContext设置为自身。您可以在页面声明中执行此操作,例如@Muzib,我尝试了 x:Bind 并找出了错误。将其发布在我的答案中。