在绑定之前更改TextBox值

时间:2018-02-16 15:05:30

标签: c# wpf xaml mvvm

如下面给出一个简单的绑定TextBox,有没有办法在/之前改变字符串?

我将文本绑定到RowFilter。所以字符串的作用是" DATA LIKE'%exampletext%'" ,我希望用户只需输入" exampletext"然后在绑定之前将文本包装在另一个字符串中。

<TextBox x:Name="Filter" Text="{Binding example, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

3 个答案:

答案 0 :(得分:2)

处理此问题的正确位置将在源(example)属性的setter中。

如果您因某些原因不想这样做,您可以在设置之前摆脱绑定并处理视图中TextChanged的{​​{1}}事件来源属性:

TextBox

<强> XAML:

private void Filter_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    string text = textBox.Text;
    //modify the text...
    string modifiedText = "...";
    //...and set the source property
    dynamic viewModel = textBox.DataContext;
    viewModel.example = modifiedText;
}

没有&#34; before-source-property-is-set&#34;事件

另一种可能的解决方案是使用值转换器:http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

答案 1 :(得分:0)

您可以尝试将完整的字符串存储在Viewmodel / code后面(DATA LIKE'%exampletext%) 然后在Textbox.Text绑定中使用一些自定义转换器,当从代码中编辑值时,将仅显示“exampletext”(将调用Convert方法),或者在值为字符串时在字符串值中写入“DATA LIKE'%exampletext%”从UI设置(将调用ConvertBack方法)

答案 2 :(得分:0)

绑定到viewmodel中的Filter字符串工作,然后在它设置工作时更改它。

    public string Filter
    {
        get { return _Filter; }
        set {

            MainVM.Modules.AllModules[0].Vwr.Table.dv.RowFilter = "PN LIKE '%" + _Filter + "%'";
            _Filter = value; OnPropertyChanged(nameof(Filter)); }
    }
    private string _Filter = "";
相关问题