将自制用户控件的属性绑定到主视图模型的属性

时间:2011-06-29 13:12:48

标签: c# wpf xaml data-binding

我有一个wpf应用程序,我扩展了RichTextBox以提供一些特定的功能。让我们称之为新类BetterTextBox。

现在,当我点击TextBox TextBox.OnPreviewMouseLeftButtonUp时,我正在获取CaretPosition:

    protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        PressedOffset = Document.ContentStart.GetOffsetToPosition(CaretPosition);      
    }

    public static readonly DependencyProperty PressedOffsetProperty 
          = DependencyProperty.Register("PressedOffset", typeof(int),
            typeof(ByteViewTextBox),
            new FrameworkPropertyMetadata()
        {
            DefaultValue = 0,
            BindsTwoWayByDefault = true,
            DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
        });

    public int PressedOffset
    {
        get { return (int)GetValue(PressedOffsetProperty); }
        set { SetValue(PressedOffsetProperty, value); Console.WriteLine("klöjgf");}
    }

XAML:

<Window x:Name="MainWindow">
    <BetterTextBox />
</Window>

MainWindow将MainViewModel作为DataContext。我想要做的是,当发生BetterTextBox中的MouseClick时,应该调用MainViewModel中的函数。如何在MainViewModel中调用函数调用我的UserControl?

我试过这样的事情:

<Window x:Name="MainWindow">
   <BetterTextBox PressedOffset="{Binding ElementName=MainWindow, Path=MyFunction"/>
</Window>

MainViewModel:

public int MyFunction
{
     set { callMyRealFunction(); }
}

但这不起作用。还有一种为PressedOffsetProperty注册CallbackFunction的方法,但我不知道如何在MainViewModel中注册一个非静态的函数。

2 个答案:

答案 0 :(得分:0)

创建ICommand类型的另一个依赖项属性,说“TextClickCommand”。 在viewmodel中创建一个命令并绑定到TextClickCommand并在MouseClick上执行它。

编辑: 你甚至可以在文本框中创建一个IsTextSelected bool依赖项属性,使用视图模型中的propery并在视图模型属性setter中调用你的方法。

答案 1 :(得分:0)

刚刚解决了

<BetterTextBox PressedOffset="{Binding Path=Parent.DataContext.SelectFromOffset,
      RelativeSource={RelativeSource Self}}"/>

来自WPF Usercontrol interaction with parent view / viewmodel