![](/img/trans.png)
[英]Defining UserControl Properties and binding them in windows phone
[英]UserControl Binding MVVM in Windows Phone 8
我有一個帶有文本框的簡單用戶控件
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); }
}
textblock是一個很好的價值,我可以讓文本做類似的事情:myusertextbox.Text
但是我想用用戶控件中文本框的值自動設置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
route。
它應該是這樣的:
private String mytext;
public String myText
{
get { return myText; }
set
{
mytext = value;
NotifyPropertyChanged("myText");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.