【问题标题】:RelayCommand in ViewModel: invocation does not have access to bound UI data in ViewModelViewModel 中的 RelayCommand:调用无权访问 ViewModel 中的绑定 UI 数据
【发布时间】:2012-01-15 15:02:07
【问题描述】:

我正在实现一个基本的搜索文本框->按钮,但我也希望用户能够按 How to enable enter button on keyboard on wp7? 键盘/键盘上的 Enter/Return 键

当调用 RelayCommand 时,我只得到一个空值作为搜索文本框的内容。

我正在使用 MVVM Light。

我有一个 PhoneApplicationPage 绑定到具有以下属性的 ViewModel:

public class MainViewModel : ViewModelBase

{

private string _searchString;

public RelayCommand Search { get; private set; }
public RelayCommand<KeyEventArgs> SearchTextBoxKeyDown { get; private set; }

public string SearchString
{
    get { return _searchString; }
    set
    {
        if (_searchString != value)
        {
            _searchString = value;
            RaisePropertyChanged("SearchString");
        }
    }
}

public MainViewModel()
{
    if (IsInDesignMode)
    {
        // Code runs in Blend --> create design time data.
    }
    else
    {
        // Code runs "for real"
        SearchTextBoxKeyDown=new RelayCommand<KeyEventArgs>((e)=>
        {
            if (e.Key == Key.Enter)
            {
                // SearchString is empty here?
                Search.Execute(null);
            }
        });
        Search = new RelayCommand(() =>
        { // invokes Search with SearchString

        },
        () =>
        {
            bool isEnabled = true;
            if (string.IsNullOrWhiteSpace(SearchString)) isEnabled = false;
            return isEnabled;
        });
    }
}

View 使用 MVVM Light 工具包调用 AutoComplete 控件上的 KeyDown 方法(它是 Telerik 控件,但它看起来像 TextBox,闻起来像 TextBox):

                <telerikInput:RadAutoCompleteBox
                    InputScope="Search"
                    Text="{Binding SearchString,Mode=TwoWay}"
                    SuggestionsSource="{Binding MruSearchStrings}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="KeyDown">
                            <cmd:EventToCommand x:Name="searchStringTextBoxKeyDown" Command="{Binding SearchTextBoxKeyDown, Mode=OneWay}" PassEventArgsToCommand="True">
                            </cmd:EventToCommand>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </telerikInput:RadAutoCompleteBox>

在调用的代码中,当我访问 SearchString 时,我只是得到 null,这是 TextBox 所绑定的 - 即使我已经在其中输入了文本。就好像 SearchTextBox 没有将其数据发送回 ViewModel 以供 ViewModel 在事件代码中获取。

我做错了什么?

【问题讨论】:

    标签: windows-phone-7 mvvm-light


    【解决方案1】:

    您的 ViewModel 没有使用来自 TextBox 的值进行更新,因为当您按下 Enter 时,您仍然拥有 TextBox 中的焦点。默认情况下,ViewModel 将在您离开 TextBox 控件后更新。但是,您可以通过使用自定义行为来改变这种情况。这个对我有用 像一个魅力:http://zoltanarvai.com/2009/07/22/binding-update-on-textbox-textchanged-event-using-behaviors/

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      相关资源
      最近更新 更多