私はyatzeeゲームを作ってWPFを学習しています。しかし、今私は私の "現在のロール"カウンターがビューで更新されない理由を理解できません。私はダイスを作って、ロールダイスボタンは私のダイスに新しい値を与えました - これはビューで更新されます。しかし、私の "現在のロール"変数はそうではありません。これはこれまで私が行ってきたことです。私は自分の値をINotifyPropertyChangedを使って更新することができません
// 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>
関連性がありません:*パブリック*フィールドと*パブリック*プロパティがそのフィールドに基づいています。また、プロパティを介してフィールドに直接*および*アクセスします。これは遅かれ早かれあなたの顔に逆行するでしょう。 – Fildor
@Fildor:なぜ「無関係」ですか?それはまさにここの問題です:) –
@DanielHilgarthああ、私はそれが実際に完全に問題を解決するとは思っていませんでした。 – Fildor