【发布时间】:2014-12-30 15:36:52
【问题描述】:
我有一个双向绑定的问题,从源到目标都可以正常工作,但是目标上的更新永远不会传播到源。
我在 DataGrid 中显示了一个自定义 UserControl,它显示了带有星号的评分:
* View.xaml
<DataGrid x:Name="Datagrid" Style="{StaticResource ResourceKey=DataGridStyle}" Grid.Row="1" AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Path=GameList}" SelectedItem="{Binding Path=SelectedGame}" SelectionChanged="datagrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Binding="{Binding Title}" />
<DataGridTemplateColumn Header="Rating" SortMemberPath="Rating">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<controls:RatingControl NumberOfStars="{Binding Path=Rating}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
* RatingControl.xaml.cs
public partial class RatingControl : UserControl
{
#region Public Dependency properties
public int NumberOfStars
{
get { return (int)GetValue(NumberOfStarsProperty); }
set { if ((int)GetValue(NumberOfStarsProperty) != value) { SetValue(NumberOfStarsProperty, value); } }
}
public static readonly DependencyProperty NumberOfStarsProperty =
DependencyProperty.Register("NumberOfStars", typeof(int), typeof(RatingControl),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnRatingChanged));
#endregion
[...]
private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
NumberOfStars = tempRating;
}
* Game.cs
public class Game : INotifyPropertyChanged
{
private int _rating;
public int Rating
{
get { return _rating; }
set { _rating = value; RaiseChangedEvent("Rating"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaiseChangedEvent(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
当我单击 RatingControl 上的星号时,我更新了 NumberOfStars 依赖属性,但我的模型的 Rating 属性没有更新。我错过了什么?
【问题讨论】:
-
{Binding Path=Rating, Mode=TwoWay} here 或在注册控件的依赖属性时将 TwoWay 绑定模式设置为默认值。
-
不,你读我的问题有点太快了。这不是必需的,因为我在 DependencyProperty 中指定了 FrameworkPropertyMetadataOptions.BindsTwoWayByDefault。
-
是的,请原谅我。顺便说一句,你不应该检查这个'if ((int)GetValue(NumberOfStarsProperty) != value',因为设计者绕过了属性访问。
-
我不记得 FrameworkMetadataOptions 的默认更新触发器是什么...
-
我想是 PropertyChanged...
标签: c# wpf xaml data-binding wpfdatagrid