14

構文を使用して、ViewModel のプロパティにバインドされListBoxた ItemContainer のプロパティがあります。IsSelectedIsSelected<ListBox.ItemContainerStyle>

正常に動作しますが、Resharper の警告が表示されます。

タイプ「FooSolution.BarViewModel」のデータ コンテキストでプロパティ「IsSelected」を解決できません。

この警告を取り除くには、ListBox ItemContainer で DataContext タイプを指定するにはどうすればよいですか?

これがコードです。私はBarViewModelクラスを持っています:

public ObservableCollection<FooViewModel> FooItems { get;set; }

BarViewModelListBox を含むコントロールの DataContext に割り当てられます

そしてFooViewModel次のように:

public bool IsSelected
{
    get
    {
        return isSelected;
    }

    set
    {
        if (isSelected == value)
        {
            return;
        }

        isSelected = value;
        RaisePropertyChanged(() => IsSelected);
    }
}

XAML は次のようになります。

<ListBox ItemsSource="{Binding FooItems}" SelectionMode="Multiple">        
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

更新HighCore で提案されているように、セッターを使用して 設定しようとしましd:DataContextたが、残念ながら、それは役に立たず、ビルドを壊すことさえあります:

<Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemViewModelClass}"/>

(スロー: エラー 1 The tag 'DesignInstance' does not exist in XML namespace 'schemas.microsoft.com/expression/blend/2008';. Line 31 Position 50. )

更新 2 最後に、解決策はスタイル要素自体に設定d:DataContextすることです (下記の私の回答を参照してください)。

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:FooViewModel }">
        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
    </Style>

4

4 に答える 4

18

@HighCore で指摘されているように、解決策はd:DataContextブレンド SDK から属性を指定することですが、プロパティ セッターではなく、Style 要素自体に設定されている場合にのみ機能します。

<ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:FooViewModel }">
            <Setter Property="IsSelected" Value="{Binding IsSelected}" />
        </Style>
</ListBox.ItemContainerStyle>

これにより、Resharper の警告が削除され、ViewModel でプロパティの名前が変更されたときにバインディング パスも変更されます。涼しい!

于 2013-03-05T19:39:00.743 に答える
3

次のように使用d:DataContextします。

<Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemViewModelClass}"/>

xmlnsまた、ルート要素に次の es を追加する必要があります。

     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d"
于 2013-03-05T18:35:43.360 に答える