【问题标题】:DataBind variable to ListBox.SelectedItem propertyDataBind 变量到 ListBox.SelectedItem 属性
【发布时间】:2011-08-10 20:21:30
【问题描述】:

我有一个正确填充的 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 上有名为“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});

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

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

【问题讨论】:

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


    【解决方案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
        });
    

    【讨论】:

    • 如此简单.. 似乎我总是这样做。谢谢!
    • 假设我在 MyUserControl 中有另一个用户控件,它有另一个我想绑定到 CurrentSource 的变量。我该怎么做?我有以下内容: anotherControl.SetBinding(anotherControl.currentSourceInfoProperty, new Binding() { Source = CurrentMapSource, Path = new PropertyPath("SourceInfo") });但它也不会在第一次之后更新。
    • 你很好com...再次:o)
    猜你喜欢
    • 2014-03-22
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多