首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将具有集合容器的复合集合从xaml转换为C#

将具有集合容器的复合集合从xaml转换为C#
EN

Stack Overflow用户
提问于 2013-03-20 04:16:51
回答 1查看 1.5K关注 0票数 1

基本上,我想将我在xaml中做的事情转换成C#。这与以下问题有关:Bind a string in xaml to a property

下面是为什么在我的例子中需要和使用代理的原因:http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

代理类来允许我绑定到CollectionContainer:

代码语言:javascript
运行
复制
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

在我的控件资源中定义的代理:

代码语言:javascript
运行
复制
<UserControl.Resources>
   <global:BindingProxy x:Key="proxy" Data="{Binding }" />
</UserControl.Resources>

我最终想要转换成C#的Xaml代码:

代码语言:javascript
运行
复制
<ComboBox ItemsSource="{Binding NameCollection}">
   <ComboBox.ItemsSource>
      <CompositeCollection>
         <x:StaticExtension Member="VM:NameClass.NoName " />
         <CollectionContainer Collection="{Binding Data.NameCollection, Source={StaticResource proxy}}" />
      </CompositeCollection>
   </ComboBox.ItemsSource>
 </ComboBox>

字符串常量,我不希望它出现在我的View Model集合中,但希望显示给用户:

代码语言:javascript
运行
复制
public class NameClass
{
   public const string NoName = "[None]";
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-20 07:48:10

我想我把它复杂化了,因为我试图包含代理。但实际上这是一个非常简单的解决方案:

代码语言:javascript
运行
复制
 ComboBox comboBox1 = new ComboBox { Height = 18, Width = 100, FontSize = 9.5 };

 CompositeCollection compositeCollection = new CompositeCollection();
 compositeCollection.Add(NameClass.NoName);

 CollectionContainer collectionContainer = new CollectionContainer();
 collectionContainer.Collection = ItemsSource1;

 compositeCollection.Add(collectionContainer);

 comboBox1.ItemsSource = compositeCollection;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15509551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档