0
我所有的数据绑定都可以在整个应用程序中工作。我已经尝试了数据绑定ItemsSource的每种模式。该列表在开始时加载,但在使用我制作的上下文菜单时不会更新。我已使用WriteLine
进行测试,以确保其他所有功能都能正常工作,而且确实如此。我的列表框在删除或添加项目时不会更新,尽管数据绑定
XAML
<ListBox Grid.Row="1" SelectionMode="Single" BorderThickness="0"
SelectionChanged="ListBox_SelectionChanged"
SelectedIndex="{Binding Path=Data.SelectedFeedIndex, Mode=TwoWay}"
SelectedItem="{Binding Path=Data.SelectedFeed, Mode=TwoWay}"
ItemsSource="{Binding Path=Data.Feeds}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Title}" MouseDown="TextBlock_MouseDown" />
<TextBox Text="{Binding Path=Title}"
Visibility="Collapsed" KeyDown="TextBox_KeyDown" Padding="1" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="New" Command="{Binding Path=Data.NewFeed}" />
<MenuItem Header="Delete" Command="{Binding Path=Data.DeleteFeed}" />
</ContextMenu>
</ListBox.ContextMenu>
<ListBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding Path=Data.DeleteFeed}" />
</ListBox.InputBindings>
</ListBox>
属性
private List<Feed> _Feeds = new List<Feed>();
public List<Feed> Feeds
{
get
{
return _Feeds;
}
set
{
_Feeds = value;
onPropertyChanged("Feeds");
}
}
命令
public ICommand DeleteFeed
{
get
{
return new RelayCommand(ExecuteDeleteFeed, CanDeleteFeed);
}
}
public void ExecuteDeleteFeed(object parameter)
{
Feeds.RemoveAt(SelectedFeedIndex);
SelectedFeedIndex = nextIndex;
onPropertyChanged("Feeds");
}
public bool CanDeleteFeed(object parameter)
{
return Feeds.Count > 1;
}
我收到中通过与上述列表框结合DEX:
private int _SelectedFeedIndex;
public int SelectedFeedIndex
{
get
{
return _SelectedFeedIndex;
}
set
{
_SelectedFeedIndex = value;
onPropertyChanged("SelectedFeedIndex");
}
}
编辑
我试图改变到ObservableCollection
,但我得到了下面的错误。
System.Windows.Data Error: 40 : BindingExpression path error: 'Feeds' property not found on 'object' ''Library' (HashCode=60811181)'. BindingExpression:Path=Data.Feeds; DataItem='MainViewModel' (HashCode=34760343); target element is 'ListBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Feeds' property not found on 'object' ''Library' (HashCode=60811181)'. BindingExpression:Path=Data.Feeds; DataItem='MainViewModel' (HashCode=34760343); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
新属性
ObservableCollection<Feed> Feeds = new ObservableCollection<Feed>();
哦,没关系。我把它变成了一个财产。它现在有效。非常感谢。我以为你只需要ObservableCollection,如果你没有手动使用INotifyProperty的所有属性。现在有道理。
即使对类中的所有属性使用INotifyProperty,它也不起作用?我现在正在尝试,但我得到一个错误。我会将其添加到帖子中。 – Expotr 2015-02-11 23:09:11
啊,你需要在集合类本身上添加INotifyCollectionChanged,这样ListBox可以看到何时添加和删除了集合中的项目。 INotifyPropertyChanged将用于Feed类以通知属性值的更改。 – 2015-02-11 23:23:09