1

この質問MVVMとTextBoxのSelectedTextプロパティを見つけました。しかし、私は解決策を機能させるのに苦労しています。これは機能していないコードで、最初のテキストボックスで選択したテキストを2番目のテキストボックスに表示しようとしています。

意見:

SelectedTextとTextは、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

}

私は何が間違っているのですか?

4

5 に答える 5

1

In order for the SelectedTextChanged handler to fire the SelectedText property must have an initial value. If you don't initialize this to some value (string.Empty as a bare minimum) then this handler will never fire and in turn you'll never register the tb_SelectionChanged handler.

于 2010-04-05T17:30:05.050 に答える
1

これが機能しない理由は、プロパティ変更コールバックが発生していないためです(VMからのバインドされた値は、プロパティのメタデータで指定されたデフォルト値と同じであるため)。ただし、より基本的には、選択したテキストがnullに設定されていると、動作が切り離されます。このような場合、選択したテキストの監視を有効にするために単に使用される別の添付プロパティを使用する傾向があります。これにより、SelectedTextプロパティをバインドできます。だから、そのようなもの:

#region IsSelectionMonitored
public static readonly DependencyProperty IsSelectionMonitoredProperty = DependencyProperty.RegisterAttached(
    "IsSelectionMonitored",
    typeof(bool),
    typeof(PinnedInstrumentsViewModel),
    new FrameworkPropertyMetadata(OnIsSelectionMonitoredChanged));

[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static bool GetIsSelectionMonitored(TextBox d)
{
    return (bool)d.GetValue(IsSelectionMonitoredProperty);
}

public static void SetIsSelectionMonitored(TextBox d, bool value)
{
    d.SetValue(IsSelectionMonitoredProperty, value);
}

private static void OnIsSelectionMonitoredChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    TextBox tb = obj as TextBox;
    if (tb != null)
    {
        if ((bool)e.NewValue)
        {
            tb.SelectionChanged += tb_SelectionChanged;
        }
        else
        {
            tb.SelectionChanged -= tb_SelectionChanged;
        }

        SetSelectedText(tb, tb.SelectedText);
    }
}
#endregion

#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)
    {
        tb.SelectedText = e.NewValue as string;            
    }
}

static void tb_SelectionChanged(object sender, RoutedEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        SetSelectedText(tb, tb.SelectedText);
    }
}
#endregion

次に、XAMLで、そのプロパティを最初のTextBoxに追加する必要があります。

<TextBox ... local:TextBoxHelper.IsSelectionMonitored="True" local:TextBoxHelper.SelectedText="{Binding SelectedText, Mode=OneWayToSource}" />
于 2010-04-06T15:34:10.147 に答える
1

これは、TextBoxHelperクラスを使用して機能します。他に述べたように、TextBoxHelperのSelectedTextプロパティをnull以外の値で初期化する必要があります。ビューの文字列プロパティ(SelText)にデータをバインドする代わりに、INotifyPropertyChangedを実装するVMの文字列プロパティにバインドする必要があります。

XAML:

<Window x:Class="TextSelectDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TextSelectDemo"
    Height="300" Width="300">
    <StackPanel>
        <TextBox local:TextBoxHelper.SelectedText="{Binding Path=SelText, Mode=TwoWay}" />
        <TextBox Text="{Binding Path=SelText}" />
    </StackPanel>
</Window>

背後にあるコード:

using System.ComponentModel;
using System.Windows;

namespace TextSelectDemo
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public Window1()
        {
            InitializeComponent();

            SelText = string.Empty;

            DataContext = this;
        }

        private string _selText;
        public string SelText
        {
            get { return _selText; }
            set
            {
                _selText = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("SelText"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
于 2010-04-06T16:20:07.337 に答える
0

バインディングは、のプロパティをの現在のデータコンテキストTextのプロパティにバインドしようとします。データコンテキストからぶら下がっているプロパティではなく、アタッチされたプロパティを使用しているため、バインディングでより多くの情報を提供する必要があります。TextBoxSelectedTextTextBox

<TextBox Text="{Binding local:TextBoxHelper.SelectedText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" ... />

クラスlocalを含むCLR名前空間に関連付けられている場所。TextBoxHelper

于 2010-04-05T18:45:43.467 に答える
-1

依存関係プロパティには、次のような通常の.netプロパティラッパーが必要です。

public string SelectedText
{
   set {SetSelectedText(this, value);}
...

ランタイム(ランタイム使用set / get)には必要ありませんが、デザイナーとコンパイラーには必要です。

于 2010-04-05T17:25:06.400 に答える