【发布时间】:2014-02-19 05:49:30
【问题描述】:
当在 ComboBox SelectedValue 属性上调用函数时,我发现 GetBindingExpression() 的一个奇怪行为。
它在第一次调用时工作正常,但在返回的 BindingExpression 上调用 UpdateTarget() 后,此 BindingExpression 似乎已从属性中删除。下一次 GetBindingExpression() 从属性返回 null。
BindingExpression exp;
// call it first time, returns an expression, and UpdateTarget success.
exp = ((ComboBox)obj).GetBindingExpression(ComboBox.SelectedValueProperty);
// call UpdateTarget
if (exp != null) exp.UpdateTarget();
// call it the second time, and now it returns null!
exp = ((ComboBox)obj).GetBindingExpression(ComboBox.SelectedValueProperty);
if (exp != null) exp.UpdateTarget();
如果我删除对 UpdateTarget() 的调用,那么下一个 GetBindingingExpression() 仍会返回一个有效的 BindingExpression。
CheckBox 的 IsChecked 属性不会发生此类问题。它总是与 CheckBox 的 IsChecked 属性一起正常工作。
XAML 如下所示:
<Style TargetType="{x:Type ComboBox}" x:Key="GainComboBoxStyle_0x00000022">
<Setter Property="Height" Value="20" />
<Setter Property="MaxWidth" Value="80" />
<Setter Property="FontFamily" Value="Calibri"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="FontWeight" Value="UltraBold"/>
<Setter Property="Tag" Value="{StaticResource moduleGain_0x00000022}" />
<Setter Property="Visibility" Value="{Binding Mode=OneWay, Converter={StaticResource getVisibilityOfGainConverter}}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Mode=OneWay, Converter={StaticResource isShowingGain}}" Value="True">
<Setter Property="SelectedValue" Value="{Binding Path=., RelativeSource={RelativeSource Mode=Self}, Mode=OneWay, Converter={StaticResource getGainValue}}"/>
<Setter Property="DisplayMemberPath" Value="Name" />
<Setter Property="SelectedValuePath" Value="Name" />
<Setter Property="IsSynchronizedWithCurrentItem" Value="False" />
<Setter Property="ItemsSource" Value="{Binding Path=GainQ13Indices, Mode=OneTime}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style TargetType="{x:Type CheckBox}" x:Key="EnableCheckBoxStyle_0x00000010">
<Setter Property="MaxWidth" Value="16"/>
<Setter Property="Tag" Value="{StaticResource
moduleEnable_0x00000010}" />
<Setter Property="Visibility" Value="{Binding Mode=OneWay, Converter={StaticResource getVisibilityOfEnableConverter}}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Mode=OneWay, Converter={StaticResource isShowingEnable}}" Value="True">
<Setter Property="IsChecked" Value="{Binding Path=., RelativeSource={RelativeSource
Mode=Self}, Mode=OneWay,
Converter={StaticResource
moduleEnableDisableConverter} }" />
</DataTrigger>
</Style.Triggers>
</Style>
为什么 UpdateTarget() 会从 ComboBox 的 SelectedValue 属性中删除 BindingExpression?为什么它适用于 CheckBox 的 IsChecked 属性?
【问题讨论】:
-
第二次仍然选择该项目吗?
-
你能用 SelectedItem 代替 SelectedValue 试试吗?
-
是的,它仍然被选中,你可以看到两个调用是并排的。第一个成功,第二个为空。我不能使用 SelectedItem,因为 BindingSource 仅用作输入并由未知数量的 ComboBoxes 共享以初始化它们的列表。绑定是一次性的,否则 ComboBox 会相互干扰。