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 -遗传/

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

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));
}

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

<UserControl.Resources>
   <global:BindingProxy x:Key="proxy" Data="{Binding }" />
</UserControl.Resources>

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

<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>

我不想在我的视图模型集合中但希望向用户显示的字符串常量:

public class NameClass
{
   public const string NoName = "[None]";
}
4

1 回答 1

0

我想我是通过尝试包含代理来使其复杂化。但实际上这是一个非常简单的解决方案:

 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;
于 2013-03-19T23:48:09.683 回答