基本上我想将我在 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]";
}