【发布时间】:2016-07-10 16:56:41
【问题描述】:
我正在制作一个基于列表框的名为“FileSelector”的用户控件。列表框填充了一个 observablecollection "FileDisplay",其中包含从对话框中选择的文件名。
<ListBox x:Name="FileListBox" Template="{DynamicResource BaseListBoxControlStyle}" Grid.RowSpan="5" Grid.Row="1" Margin="0" ItemContainerStyle="{DynamicResource BaseListBoxItemStyle}" ItemsSource="{Binding DataContext.FileDisplay, ElementName=F_Selector, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<DockPanel>
<Button x:Name="ListDelete" Width="{Binding ActualHeight, ElementName=ListDelete}" Style="{DynamicResource BaseButtonStyle}" Margin="4,0,0,0" DockPanel.Dock="Right" Content="X" Click="FileDelete_Click"/>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<ToggleButton x:Name="ListCheck" Width="{Binding ActualHeight, ElementName=ListCheck}" Style="{DynamicResource BaseToggleButtonStyle}" Margin="0,0,4,0" Checked="File_Checked" Unchecked="File_Unchecked" />
<TextBlock Text="{Binding ., Converter={StaticResource PathToFileName}}" TextTrimming="CharacterEllipsis"/>
</StackPanel>
</DockPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
当检查项目中包含的切换按钮时,我想将项的内容添加到DeviewableCollection类型的DependencyProperty。
private void File_Checked(object sender, RoutedEventArgs e)
{
ToggleButton btn = (ToggleButton)sender;
int index = FileListBox.Items.IndexOf(btn.DataContext);
FileChecked[index] = true;
FileSelected.Add(FileDisplay[index]);
}
依赖属性:
public static readonly DependencyProperty FileSelectedProperty =
DependencyProperty.Register("FileSelected", typeof(ObservableCollection<string>), typeof(FileSelector));
[Bindable(true)]
public ObservableCollection<string> FileSelected
{
get { return (ObservableCollection<string>)this.GetValue(FileSelectedProperty); }
set { this.SetValue(FileSelectedProperty, value); }
}
此外,FileChecked 是一个 observablecollection,用于跟踪检查哪个元素以供以后使用。
一切都编译得很好,但是当我检查一个切换按钮时,会抛出这个错误:
Access violation at address 00007FFA2981CC85. Read of address 0000000000000000.
值得注意的是,如果我将 DependencyProperty FileSelected 更改为一个简单的 observablecollection 是没有问题的,但我不想这样做,因为我以后无法绑定它。
知道为什么吗?谢谢你
编辑---- 在使用visualstudio调试器进行更多测试后,我发现每当我点击一个切换按钮时,名为“FileSelected”的依赖属性为空,而即使我用任何类型的字符串替换最新的,它也应该添加“FileDisplay [index]”。 ..
【问题讨论】:
标签: c# wpf user-controls observablecollection dependency-properties