0

WPF でデータバインドされたラジオボタン リストボックスを取得して、ユーザー入力に応答し、バインド先のデータへの変更を反映する (つまり、コードを変更する) 際に問題が発生しています。ユーザー入力側は正常に動作します (つまり、ラジオボタンを選択でき、リストが期待どおりに動作します)。ただし、コードで選択を変更しようとすると、すべて失敗します。静かに (つまり、例外なく)。

XAMLの関連セクションは次のとおりです(私は思います):

<Setter Property="ItemContainerStyle">
<Setter.Value>
    <Style TargetType="{x:Type ListBoxItem}" >
        <Setter Property="Margin" Value="2" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border Name="theBorder" Background="Transparent">
                    <RadioButton Focusable="False" IsHitTestVisible="False" 
                        IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" >
                        <ContentPresenter />
                    </RadioButton>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Setter.Value>

リスト ボックスを SchoolInfo オブジェクトの List にバインドします。SchoolInfo には IsSelected というプロパティが含まれています。

    public bool IsSelected
    {
        get { return isSelected; }

        set
        {
            if( value != isSelected )
            {
                isSelected = value;
                this.OnPropertyChanged("IsSelected");
            }
        }
    }

OnPropertyChanged() のものは、実験中に入れたものです。問題は解決しません。

次のようなものは失敗します。

((SchoolInfo) lbxSchool.Items[1]).IsSelected = true;
lbxSchool.SelectedIndex = 1;

それらは黙って失敗します。例外はスローされませんが、UI には選択されている項目が表示されません。

4

2 に答える 2

2

RadioButton は、SchoolInfo IsSelected プロパティではなく、ListBoxItem IsSelected プロパティにバインドされています。

(ListBoxItem には「IsSelected」プロパティがあり、SchoolInfo オブジェクトも同様であるため、混乱します。これがバインディング エラーが発生しなかった理由です)。

修正するには、ListBoxItem.IsSelected を SchoolInfo IsSelected プロパティにバインドする必要があります。

つまり、ListBoxItem を SchoolInfo.IsSelected にバインドするための追加のセッターが必要です。そうすれば、リスト ボックス項目は正常に機能し、RadioButton も ListBoxItem.IsSelected に正しくバインドできます。

<Style TargetType="{x:Type ListBoxItem}" >
    <Setter Property="IsSelected" Value="{Binding Path=IsSelected}" />
于 2010-02-04T18:54:07.830 に答える
0

RadioButton バインディングで NotifyOnSourceUpdated を有効にします。双方向バインディング (デフォルト) を許可している場合でも、明示的にリッスンしない限り、コード ビハインドの変更から通知が取得されることはありません。

<RadioButton Focusable="False" IsHitTestVisible="False" 
                    IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource TemplatedParent}, NotifyOnSourceUpdated=True}" >
于 2010-02-04T18:38:12.473 に答える