0
我有一个ComboBox,其内容是数据绑定到2个依赖项属性(Foo
和Bar
)的2个项目。 我有一个按钮,它增加了Foo
和Bar
。 当我按下此按钮时,我在输出窗口中看到Foo
和Bar
的确已发生变化。在绑定上设置断点(仅限SL 5)也证明了这一点。 但ComboBox上显示的值未更新! 只有当我点击组合框或通过[TAB]和[DOWN]更改所选项目时,它才会更新。数据绑定ComboBox在值更改后未立即刷新
我甚至试图在值更新后在我的ComboBox上调用UpdateLayout()
,但无济于事。
这是我的代码供您测试。
后面的代码:
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
namespace ComboBoxBindingTest
{
public partial class MainPage : UserControl
{
public int Foo
{
get { return (int)GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
public static readonly DependencyProperty FooProperty =
DependencyProperty.Register("Foo", typeof(int), typeof(MainPage), new PropertyMetadata(0));
public int Bar
{
get { return (int)GetValue(BarProperty); }
set { SetValue(BarProperty, value); }
}
public static readonly DependencyProperty BarProperty =
DependencyProperty.Register("Bar", typeof(int), typeof(MainPage), new PropertyMetadata(0));
public MainPage()
{
Foo = 0;
Bar = 0;
InitializeComponent();
DataContext = this;
}
private void Step()
{
Foo++;
Bar++;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Step();
Debug.WriteLine("Foo: {0}", Foo);
Debug.WriteLine("Bar: {0}", Bar);
}
}
}
XAML:
<UserControl x:Class="ComboBoxBindingTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="138"
d:DesignWidth="188">
<StackPanel Background="White">
<ComboBox Width="120"
Height="23"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ComboBoxItem Content="{Binding Foo}"
IsSelected="True" />
<ComboBoxItem Content="{Binding Bar}" />
</ComboBox>
<Button Content="Step"
Width="75"
Height="23"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Click="Button_Click" />
</StackPanel>
</UserControl>
我在做什么错了,在这里?
谢谢您的anwser!明天我会试一试。 – Rodolphe 2011-12-22 19:53:21
对不起,这是一段时间...我现在使用'ObservableCollection'并且一切正常。非常感谢! – Rodolphe 2012-02-03 15:33:06