我正在构建一个Windows Phone 8应用程序。我有一个UserControl,其内容应异步更新。我的模型实现了INotifyPropertyChanged。当我更新模型中的值时,它会传播到TextBox控件,但不会传播到UserControl的内容。 我错过了哪个部分,或者它是不可能的? 这是我的复制场景。
应用页面:
<phone:PhoneApplicationPage x:Class="BindingTest.MainPage">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Click="Button_Click" Content="Click" HorizontalAlignment="Left" Margin="147,32,0,0" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="69,219,0,0" TextWrapping="Wrap" Text="{Binding Bar}" VerticalAlignment="Top" Height="69" Width="270"/>
<app:MyControl x:Name="Snafu" HorizontalAlignment="Left" Margin="69,319,0,0" Title="{Binding Bar}" VerticalAlignment="Top" Width="289"/>
</Grid>
</phone:PhoneApplicationPage>
这是模型类(Foo)背后的代码
public partial class MainPage : PhoneApplicationPage
{
Foo foo;
// Constructor
public MainPage()
{
InitializeComponent();
foo = new Foo();
ContentPanel.DataContext = foo;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foo.Bar = "Gnorf";
}
}
public class Foo : INotifyPropertyChanged
{
string bar;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public Foo()
{
Bar = "Welcome";
}
public string Bar
{
get
{
return bar;
}
set
{
bar = value;
OnPropertyChanged("Bar");
}
}
}
UserControl xaml
<UserControl x:Class="BindingTest.MyControl">
<TextBox x:Name="LayoutRoot" Background="#FF9090C0"/>
</UserControl>
UserControl背后的代码
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata("", OnTitleChanged));
static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyControl c = (MyControl)d;
c.Title = e.NewValue as String;
}
public string Title
{
get
{
return (string)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
LayoutRoot.Text = value;
}
}
}
当我运行该示例时,UserControl TextBox将包含welcome。当我单击按钮时,常规TextBox将更新为Gnorf,但UserControl仍会显示Welcome。
我还发现,如果我只绑定到UserControl,则在调用set_DataContext时,PropertyChanged事件处理程序为null。 DataBinding基础结构似乎推断出对我的UserControl的绑定是一次性绑定而不是常规的单向绑定。 有什么想法吗?
答案 0 :(得分:0)
试试这个: -
<app:UserControl1 x:Name="Snafu" Title="{Binding Bar,Mode=TwoWay}" />
我检查了它..这将有效.. :)