WindowsPhone8中的UserControl绑定MVVM
本文关键字:MVVM 绑定 UserControl 中的 WindowsPhone8 | 更新日期: 2023-09-27 18:00:21
我有一个带有文本框的简单用户控件
XAML:
<UserControl x:Name="myTextBox" x:Class="Views.UserControls.myTextBox"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}" d:DesignWidth="480" Height="92">
<StackPanel>
<StackPanel Margin="25,0,0,0" Orientation="Horizontal">
<TextBlock TextWrapping="Wrap" Text="Title" FontSize="16" HorizontalAlignment="Left"/>
</StackPanel>
<TextBox x:Name="textbox" TextWrapping="Wrap" Text="{Binding Text, Mode=TwoWay}" VerticalAlignment="Top"/>
</StackPanel>
代码背后:
public partial class LabeledTextBox : UserControl
{
public LabeledTextBox()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(String), typeof(LabeledTextBox), new PropertyMetadata(default(String)));
public String Text
{
get { return (String)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
}
还有一页:
<phone:PhoneApplicationPage
[...]
>
<phone:PhoneApplicationPage.DataContext>
<viewmodel:myViewModel/>
</phone:PhoneApplicationPage.DataContext>
<StackPannel>
<TextBlock Text="{Binding Text, ElementName=myusertextbox}"/>
<usercontrols:myTextBox x:Name="myusertextbox" Text="{Binding myText, Mode=TwoWay}"/>
</StackPannel>
在我的视图模型中:
private String mytext;
public String myText
{
get { return myText; }
set { NotifyPropertyChanged(ref myText, value); }
}
文本块是一个很好的值,我可以让文本做这样的事情:myusertextbox。文本
但我想用用户控件中文本框的值自动设置myText。
我试了一整天,但还是没用。。。
我错过了什么?提前谢谢。
编辑:
public abstract class ANotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string nomPropriete)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(nomPropriete));
}
public bool NotifyPropertyChanged<T>(ref T variable, T valeur, [CallerMemberName] string nomPropriete = null)
{
if (object.Equals(variable, valeur))
return false;
variable = valeur;
NotifyPropertyChanged(nomPropriete);
return true;
}
}
private String mytext;
public String myText
{
get { return myText; }
set { NotifyPropertyChanged(ref myText, value); }
}
您使用什么样的框架来实现INotifyPropertyChanged接口?您甚至没有在此处设置您的私人字段的值。这在我看来很奇怪。它似乎没有遵循get
-set
-notify
的路线。
它被认为是类似于:
private String mytext;
public String myText
{
get { return myText; }
set
{
mytext = value;
NotifyPropertyChanged("myText");
}
}