0

使用 Prism,我实现了与 StockTraderRI 项目非常相似的 View、Model 和 Presenter。我的问题是我正在尝试将堆栈面板数据绑定到 ObservableCollection 对象,但没有显示任何字符串。

这是我的代码:

演示模型代码:

    public InfoBarPresentationModel(IInfoBarView view, IEventAggregator eventAggregator)
    {
        this.View = view;
        this.View.Model = this;
        InfoBarItems = new ObservableCollection<string>();
        InfoBarItems.Add("Test 1");
        InfoBarItems.Add("Test 2");
    }

    public IInfoBarView View { get; set; }

    public ObservableCollection<string> InfoBarItems { get; set; }

XAML 代码:

<ItemsControl x:Name="list" ItemsSource="{Binding InfoBarItems}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Text="{Binding}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我尝试了多种绑定组合,但还没有弄清楚为什么我的字符串从未出现过。我究竟做错了什么?

瑞克

4

3 回答 3

0

以下 XAML 应该可以工作:

<ItemsControl x:Name="list" ItemsSource="{Binding Path=InfoBarItems}">
   <ItemsControl.ItemsPanel>
       <ItemsPanelTemplate>
           <StackPanel />
       </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
       <DataTemplate>
           <TextBox Text="{Binding Path=.}" />
       </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

您的方法的不同之处在于:
- DataTemplate 定义中没有 StackPanel
- 将绑定路径添加到 TextBox 绑定

于 2009-07-05T13:13:26.877 回答
0

事实证明,如果我在分配模型之前创建我的集合,它就可以工作。

原始代码:

  public InfoBarPresentationModel(IInfoBarView view, IEventAggregator eventAggregator)
    {
        this.View = view;
        this.View.Model = this;
        InfoBarItems = new ObservableCollection<string>();
        InfoBarItems.Add("Test 1");
        InfoBarItems.Add("Test 2");
    }

新代码:

  public InfoBarPresentationModel(IInfoBarView view, IEventAggregator eventAggregator)
    {
        InfoBarItems = new ObservableCollection<string>();
        InfoBarItems.Add("Test 1");
        InfoBarItems.Add("Test 2");
        this.View = view;
        this.View.Model = this;
    }

您的 xaml 和我原来的 xaml 都可以正常工作。

谢谢你。

瑞克

于 2009-07-06T17:55:43.313 回答
0

你是 PresentationModel 类实现INotifyProperytChanged吗?还是你收藏了DependencyProperty?如果不是这种情况,视图将永远不会收到您创建集合这一事实的通知。

这就是为什么如果在集合绑定到视图之前设置集合,它将起作用,而不是相反。我确实认为,INotifyPropertyChanged除非所有属性在绑定时都已修复,否则不要制作您的 PresentationModel 是不好的做法。

于 2009-07-20T12:30:00.243 回答