DataBind变量为ListBox.SelectedItem属性

时间:2011-08-10 20:21:30

标签: c# data-binding silverlight-4.0 listbox

我有一个正确填充的ListBox(lstBxsources)并且工作正常。

<ListBox Name="lstBxSources" ItemsSource="{Binding}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=Name}" ToolTipService.ToolTip="{Binding Path=Description}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我还有一个UserControl(MyUserControl)。

<MainControl:MyControl x:Name="MyUserControl" Grid.Row="1"/>

MyUserControl上有Dependency属性,名为'CurrentSourceProperty'

    public SourceInfo CurrentSource
    {
        get { return (SourceInfo)GetValue(CurrentSourceProperty); }
        set { SetValue(CurrentSourceProperty, value); }
    }

    public static readonly DependencyProperty CurrentSourceProperty =
        DependencyProperty.Register("CurrentSource", typeof(SourceInfo), typeof(MyControl), new PropertyMetadata(null));

我已将CurrentSource数据绑定到lstBxSources的SelectedItem,如下所示:

 MyUserControl.SetBinding(MyControl.CurrentSourceProperty, new Binding() { Source = lstBxSources.SelectedItem});

这最初有效,但在更改SelctedItem时不会更新。

知道为什么它不会为我更新?

1 个答案:

答案 0 :(得分:1)

知道了......像这样修复你的绑定:

MyUserControl.SetBinding(MyControl.CurrentSourceProperty,
new Binding() { 
  Source = lstBxSources, 
  Path= new PropertyPath("SelectedItem")
  });

如果我说得对,请将此代码放在MyUserControl中:

MyAnotherControl.SetBinding(AnotherControl.currentSourceInfoProperty,
    new Binding()
    {
        Source = this,
        Path = new PropertyPath("CurrentSource"),
            Mode = BindingMode.TwoWay
    });