C# 在设计时需要模拟XAML数据
我使用XAML中定义的静态对象数组作为列表框上的ItemsSource 我使用:C# 在设计时需要模拟XAML数据,c#,wpf,xaml,C#,Wpf,Xaml,我使用XAML中定义的静态对象数组作为列表框上的ItemsSource 我使用: ItemsSource="{Binding Source={StaticResource theSource}}". 这在设计时非常有效。但是,我需要在运行时覆盖它,以便列表框将从视图模型上的集合属性中获取它的项。我公开了一个名为“theSource”的属性,并在代码隐藏中设置了窗口数据上下文。但是,列表仍然绑定到静态资源。。。不是我的视图模型上的属性 有没有关于让设计时数据可视化UI并在运行时替换为实时数据的正
ItemsSource="{Binding Source={StaticResource theSource}}".
这在设计时非常有效。但是,我需要在运行时覆盖它,以便列表框将从视图模型上的集合属性中获取它的项。我公开了一个名为“theSource”的属性,并在代码隐藏中设置了窗口数据上下文。但是,列表仍然绑定到静态资源。。。不是我的视图模型上的属性
有没有关于让设计时数据可视化UI并在运行时替换为实时数据的正确方法的建议 只需命名Listbox控件即可
<ListBox x:Name="myListBox"
ItemsSource="{Binding Source={StaticResource theSource}}" />
第二,看看这个问题: 如果您使用的是WPF,那么您可以使用
DynamicResource
,并在运行时更改其定义
但是,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个成本资源?已更正并完成我的回答
<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>