基本上我想将我在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的代理类:
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>
String我在View Model集合中不需要的常量,但希望向用户显示:
public class NameClass
{
public const string NoName = "[None]";
}
答案 0 :(得分: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;