我有一個ListView,它的itemsource是元素,這是一個Schranken對象列表。 SchrankePresenter是頁面的DataContext(在構造函數中設置)。OnPropertyChanged不更新視圖
頁面顯示正確,直到單擊按鈕。如果單擊一個按鈕,該按鈕的名稱值應該更改,ListView應該有一個項目更多,但沒有任何反應/更新。
這裏是SchrankenPresenter:
public class SchrankePresenter : INotifyPropertyChanged
{
private List<Schranke> _elements;
public List<Schranke> Elements
{
get { return _elements; }
set
{
_elements = value;
OnPropertyChanged("Elements");
}
}
public ICommand ClickCommand { get; set; }
private void OnPropertyChanged(string propName)
{
Debug.WriteLine($"on Property changed with {propName}");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
public SchrankePresenter()
{
var elements = new List<Schranke>();
for (var i = 1; i < 15; i++)
elements.Add(new Schranke() { Name = $"{i}: Schranke" });
Elements = elements;
Debug.WriteLine("ctor");
ClickCommand = new DelegateCommand<Schranke>(ClickAction);
}
public void ClickAction(Schranke item)
{
VibrationDevice.GetDefault().Vibrate(TimeSpan.FromMilliseconds(150));
Debug.WriteLine($"{item?.Name} was clicked");
item.Name = "was clicked";
OnPropertyChanged("Name");
Elements.Add(new Schranke() { Name = "addednew element" });
OnPropertyChanged("Elements");
}
}
類Schranke只有一個成員:public string Name { get; set; }
的看法是這樣的:
<ListView ItemsSource="{Binding Elements, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" x:Name="lv_schranken" Grid.Row="1" SelectedItem="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<Button Height="80"
HorizontalAlignment="Stretch"
Command="{Binding ElementName=lv_schranken, Path=DataContext.ClickCommand}"
CommandParameter="{Binding}"
Style="{StaticResource TransparentStyle}">
<Grid>
.
. (some grid stuff)
.
<TextBlock Name="schranken_name"
Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontWeight="ExtraLight"
FontSize="25"
Foreground="Black"
Text="{Binding Name, Mode=TwoWay}" />
</Grid>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
PS:如果某些需求DelegateCommand - 實施:
public class DelegateCommand<T> : ICommand
{
private Action<T> _clickAction;
public DelegateCommand(Action<T> clickAction)
{
_clickAction = clickAction;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_clickAction((T)parameter);
}
}
'OnPropertyChanged(「名稱」);'應該在'Schranke'類調用,在'名稱'二傳手。 – ASh
如果你已經做了任何研究,你會知道一個不綁定到'List'。 –
是否可以使用列表進行綁定? –
student96