2011-06-29 30 views
0

我有一個wpf應用程序,我在其中擴展了RichTextBox以提供某些特定功能。讓我們調用這個新類BetterTextBox。將自制用戶控件的屬性綁定到主視圖模型的屬性

現在,當我單擊該文本框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> 

主窗口有MainViewModel作爲DataContext的。我想要做的是,當發生BetterTextBox中的MouseClick時,應該調用MainViewModel中的函數。我怎樣才能離開我的UserControl調用一個MainViewModel中的函數?

我想是這樣的:

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

MainViewModel:

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

但是,這並不工作。還有一種方法來爲PressedOffsetProperty註冊一個CallbackFunction,但我不知道如何在MainViewModel中註冊一個非靜態的函數。

回答

0

創建另一個類型爲ICommand的依賴項屬性,並說'TextClickCommand'。 在您的viewmodel中創建一個命令並綁定到TextClickCommand並在MouseClick上執行此命令。

編輯: 甚至可以通過其他方式在文本框中創建IsTextSelected布爾依賴項屬性使用視圖模型中的propery綁定到此布爾,並在視圖模型屬性設置器中調用您的方法。

+0

Sry基因做

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

就解決了,我真的不能跟着你。你能更精準嗎?我已經在做你的「編輯」而沒有運氣或沒有?我也搜索了命令,並且有一堆結果,我迷路了。 – KasF

相關問題