我找到這個問題MVVM and the TextBox's SelectedText property。但是,我無法獲得解決方案。這是我的非工作代碼,我試圖在第二個文本框中顯示第一個文本框的選定文本。MVVM-我如何綁定到屬性,這不是DependancyProperty?
查看:
SelectedText和文本都是從我的ViewModel只是字符串屬性。
<TextBox Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" Height="155" HorizontalAlignment="Left" Margin="68,31,0,0" Name="textBox1" VerticalAlignment="Top" Width="264" AcceptsReturn="True" AcceptsTab="True" local:TextBoxHelper.SelectedText="{Binding SelectedText, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}" />
<TextBox Text="{Binding SelectedText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Height="154" HorizontalAlignment="Left" Margin="82,287,0,0" Name="textBox2" VerticalAlignment="Top" Width="239" />
TextBoxHelper
public static class TextBoxHelper
{
#region "Selected Text"
public static string GetSelectedText(DependencyObject obj)
{
return (string)obj.GetValue(SelectedTextProperty);
}
public static void SetSelectedText(DependencyObject obj, string value)
{
obj.SetValue(SelectedTextProperty, value);
}
// Using a DependencyProperty as the backing store for SelectedText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedTextProperty =
DependencyProperty.RegisterAttached(
"SelectedText",
typeof(string),
typeof(TextBoxHelper),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedTextChanged));
private static void SelectedTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
TextBox tb = obj as TextBox;
if (tb != null)
{
if (e.OldValue == null && e.NewValue != null)
{
tb.SelectionChanged += tb_SelectionChanged;
}
else if (e.OldValue != null && e.NewValue == null)
{
tb.SelectionChanged -= tb_SelectionChanged;
}
string newValue = e.NewValue as string;
if (newValue != null && newValue != tb.SelectedText)
{
tb.SelectedText = newValue as string;
}
}
}
static void tb_SelectionChanged(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
SetSelectedText(tb, tb.SelectedText);
}
}
#endregion
}
我在做什麼錯?
的SelectedText屬性是一個附加的(依賴)房地產不是一個 '正常' 的依賴項屬性。有關概述,請參閱http://msdn.microsoft.com/en-us/library/ms749011.aspx – 2010-04-05 17:32:46
好吧,我在閱讀原始問題時並不十分小心。但是你不認爲投票對於想要幫助的職位太過分了嗎? – Codism 2010-04-05 21:40:07
不要讓自己陷入低谷。這只是一個工具,可以幫助人們從無用的人身上篩選有用的答案。如果您發現自己發佈了無用的答案,並且該答案已被降低,您可以將其刪除。 – RandomEngy 2010-04-06 20:56:06