Trong một số ListBox
Tôi có thuộc tính IsSelected
của ItemContain được liên kết với thuộc tính 01Mcủa ViewModel sử dụng cú pháp <ListBox.ItemContainerStyle>
.Chỉ định loại dữ liệu địa lý trên hộp danh sách ItemContainer theo kiểu
Nó hoạt động tốt, nhưng tôi nhận được một cảnh báo Resharper:
Cannot resolve property 'IsSelected' in data context of type "FooSolution.BarViewModel".
Làm thế nào để xác định rõ DataContext loại trên ListBox ItemContainer để thoát khỏi cảnh báo này?
Đây là mã. Tôi có một lớp BarViewModel
:
public ObservableCollection<FooViewModel> FooItems { get;set; }
BarViewModel
được gán cho DataContext trong Control chứa ListBox
và FooViewModel
như sau:
public bool IsSelected
{
get
{
return isSelected;
}
set
{
if (isSelected == value)
{
return;
}
isSelected = value;
RaisePropertyChanged(() => IsSelected);
}
}
và XAML như thế này:
<ListBox ItemsSource="{Binding FooItems}" SelectionMode="Multiple">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Cập nhật Tôi đã thử đặt d:DataContext
sử dụng một setter, theo đề nghị của HighCore, nhưng unfortunatelly, nó không giúp đỡ và thậm chí phá vỡ xây dựng:
<Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemViewModelClass}"/>
(Ném: Lỗi 1 Thẻ 'DesignInstance' không tồn tại trong không gian tên XML 'schemas.microsoft.com/expression/blend/2008' ;. Dòng 31 Chức 50.)
Cập nhật 2 Finaly, giải pháp là để thiết lập d:DataContext
trên các yếu tố phong cách riêng của mình (xem câu trả lời dưới đây của tôi):
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:FooViewModel }">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
+1 cả hai chúng tôi đã học được điều gì đó ngày hôm nay =) –
Tôi nhận được lỗi sau: Thuộc tính 'DataContext' không được gắn vào các phần tử kiểu 'Kiểu'. ¿? ¿? ¿ –
@somos, bạn có chắc không, bạn đang sử dụng d: DataContext từ blend SDK (đây là một prop đặc biệt kèm theo để cho phép nhà thiết kế biết về kiểu VM trong thời gian thiết kế) – Isantipov