![](/img/trans.png)
[英]How can I update FontFamily and Foreground of a data bound ListBox using INotifyPropertyChanged
[英]I can't get my value to update using INotifyPropertyChanged
因此,我正在通过编写Yatzee游戏来学习WPF,而且我正在走向某个地方。 但是现在我不明白为什么我的“当前滚动”计数器不会在视图中更新。 我完成了骰子的工作,掷骰子按钮为我的骰子提供了新值-并在视图中对其进行了更新。 但是我的“当前滚动”变量不会。 到目前为止,这是我所做的。
// CurrentRoll.cs
public class CurrentRoll : INotifyPropertyChanged
{
public int _roll;
public int Roll
{
get { return _roll; }
set
{
if (value != _roll)
{
_roll = value;
OnPropertyChanged("Roll");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
这就是我的DiceModelView。 当我点击“滚动骰子”按钮时,只要不选中它们,我就会在所有骰子上获得新值。 我还增加了_currentRoll变量,并且只允许新的滚动,只要_currentRoll仍小于3。此逻辑有效,该变量有效,但它在View中的表示无效。 我也将其初始值更改为其他值,只是为了查看绑定是否有效。
public class DiceModelView : INotifyPropertyChanged
{
Die _die;
public CurrentRoll _currentRoll;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Die> myDices { get; set; }
public ICommand RollCommand { get; set; }
public DiceModelView()
{
myDices = new ObservableCollection<Die>()
{
new Die { Id = 0, Roll = 0, Checked = false },
new Die { Id = 1, Roll = 0, Checked = false },
new Die { Id = 2, Roll = 0, Checked = false },
new Die { Id = 3, Roll = 0, Checked = false },
new Die { Id = 4, Roll = 0, Checked = false }
};
_currentRoll = new CurrentRoll();
_currentRoll._roll = 0;
RollCommand = new Command (executeMethod, canexecuteMethod);
}
public bool canexecuteMethod(object parameter)
{
return true;
}
private void executeMethod(object parameter)
{
var r = new Random();
if (_currentRoll._roll < 3)
{
foreach (Die d in myDices)
{
if (d.Checked == false)
{
d.Roll = r.Next(1, 7);
}
}
}
_currentRoll._roll++;
}
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public Die die
{
get { return _die; }
set { _die = value; }
}
public CurrentRoll currentRoll
{
get { return _currentRoll; }
set { _currentRoll = value;
NotifyPropertyChanged("currentRoll");
}
}
最后,这是我使用的XAML代码:
<Window.DataContext>
<local:DiceModelView/>
</Window.DataContext>
<StackPanel>
<TextBlock Text="{Binding currentRoll.Roll, UpdateSourceTrigger=PropertyChanged}"/>
<ListView x:Name="DiceView" ItemsSource="{Binding myDices}" Width="500" HorizontalContentAlignment="Center" >
<ListView.ItemTemplate>
<DataTemplate >
<CheckBox Content="{Binding Roll}" IsChecked="{Binding Checked}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Roll the dices!" Command="{Binding RollCommand}"/>
</StackPanel>
</Window>
您需要更新Roll
属性,而不是_role
字段。
_roll
无论如何_roll
应该是私有的。
试想一下:您正在属性设置器中引发属性更改事件,因此只有在设置属性值时才会执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.