【问题标题】:Need Mock XAML data at design time在设计时需要 Mock XAML 数据
【发布时间】:2009-11-20 08:31:24
【问题描述】:

我使用 XAML 中定义的静态对象数组作为列表框上的 ItemsSource。

我使用:

ItemsSource="{Binding Source={StaticResource theSource}}".

这在设计时效果很好。但是,我需要在运行时覆盖它,以便列表框从我的视图模型上的集合属性中获取它的项目。我公开了一个名为“theSource”的属性,并在后面的代码中设置了 Window DataContext。但是,列表仍然绑定到静态资源...而不是我的视图模型上的属性。

关于使用设计时数据来可视化 UI 并在运行时替换为实时数据的正确方法有什么建议吗?

【问题讨论】:

  • 更正并完成了我的回答

标签: c# wpf xaml


【解决方案1】:

只需命名您的列表框控件

<ListBox x:Name="myListBox" 
 ItemsSource="{Binding Source={StaticResource theSource}}" />

并在运行时更改它

myListBox.ItemsSource = datasource;

第二次解决这个问题:

What's the difference between StaticResource and DynamicResource in WPF?

如果您使用的是 WPF,那么您可以改用 DynamicResource,并在运行时更改 this 的定义

不过,Silverlight 会失败,因为这个更轻量级的框架不支持动态资源。


第三次拍摄

既然你想使用绑定到你的控制器对象,那么:

<Page xmlns="http://..." xmlns:your="...">
<Page.DataContext>
  <your:DesignTimeObject> <!-- Must be of the same type as in runtime, or at least expose properties and subproperties with the same name -->
   <your:DesignTimeObject.List>
    <your:Element id="1" />
     <your:Element id="2" />
     <!-- snip -->
   <your:DesignTimeObject.List>
  </your:DesignTimeObject>
</Page.DataContext>
<ListBox x:Name="myListBox"  ItemsSource="{Binding List}" /> <!-- Binds to the Element list with id="1" , id="2" ... -->
</Page> 

通过这种方式,您不必在运行时更改绑定,只需设置一次 DataContext 即可完成。

【讨论】:

  • 是的,我想这可行,但我正在尝试遵循模型-视图-视图模型原则。所以,我只想设置窗口数据上下文,让 WPF 绑定解析为运行时数据。不过感谢您的建议。
  • 你的第三次拍摄绝对让我走上了正轨。我使用了一个细微的变化来将 DataContext 声明为我的 CLR 对象的数组,并且 ItemSource={Binding } 这正是我所需要的。谢谢。
  • 运行时是否占用 3 个成本资源?
猜你喜欢
  • 1970-01-01
  • 2015-10-22
  • 2010-11-09
  • 2014-10-22
  • 1970-01-01
  • 2023-03-24
  • 2011-12-06
相关资源
最近更新 更多