我创建了一个usercontrol,我在Content控件DataTemplate中使用它基于选择器,如下所示。
<DataTemplate x:Key="CodeSnippetDetails">
<StackPanel >
<CodeEditor:SUITCodeEditorView FontSize="24" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" MinHeight="100" Text ="{Binding Path = DataContext.CodeText, RelativeSource ={RelativeSource FindAncestor,AncestorType ={x:Type telerik:TreeListViewRow}}}" >
</CodeEditor:SUITCodeEditorView>
</StackPanel>
我在userControl上创建了一个DependencyProperty,并且usercontrol有自己的ViewModel,名为SUITCodeEditorViewModel。
现在我想将UserControl上的Text属性绑定到ParentControl viewmodel的CodeText属性,并双向将Text属性绑定到SUITCodeEditorViewModel上的EditorText属性(usercontrol的viewmodel)。
我曾尝试使用多个绑定,但它不起作用并给出了一些例外。
我尝试创建两个依赖项属性,并尝试将一个属性绑定到ParentViewModel的CodeText属性,并将另一个依赖项属性绑定到SUITCodeEditorViewModel的EditorText属性。但它仍然没有用。
public partial class SUITCodeEditorView : UserControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set
{
var oldValue = (string)GetValue(TextProperty);
if (oldValue != value) SetValue(TextProperty, value);
}
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(SUITCodeEditorView), new PropertyMetadata(string.Empty, OnTextSet));
private static void OnTextSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
try
{
if(e.OldValue!=e.NewValue)
((SUITCodeEditorView)d).codeEditor.Text = Convert.ToString(e.NewValue);
}
catch (Exception)
{
}
}
public string ProxyText
{
get { return (string)GetValue(ProxyTextProperty); }
set
{
var oldValue = (string)GetValue(ProxyTextProperty);
if (oldValue != value) SetValue(ProxyTextProperty, value);
}
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ProxyTextProperty =
DependencyProperty.Register("ProxyText", typeof(string), typeof(SUITCodeEditorView), new PropertyMetadata(string.Empty, OnProxyTextSet));
private static void OnProxyTextSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
try
{
if (e.OldValue != e.NewValue)
OnTextSet(d, e);
}
catch (Exception)
{
}
}
public SUITCodeEditorView()
{
InitializeComponent();
var nameOfPropertyInVm = "EditorText";
var binding = new Binding(nameOfPropertyInVm) { Mode = BindingMode.TwoWay };
this.SetBinding(ProxyTextProperty, binding);
}
}
如果有任何方法可以帮助我吗?