在数据绑定期间阻止文本框为空时更新

时间:2014-01-21 03:10:52

标签: c# wpf

我有ListView,当用户选择列表视图中的项目时,它将显示在`TextBox上以进行更新。

问题是如何在用户清除SelectedItem

中的文字时阻止更新TextBox

C#代码:

private void Update_Button(object sender, RoutedEventArgs e)
{

    string fname = tb_firstname.Text;
    string lname = tb_lastname.Text;
    var selectedEmployee = (Employee)lview.SelectedItem;

    if (fname != null && lname != null)
    {
            selectedEmployee.FirstName = fname;
            selectedEmployee.LastName = lname; 
            Refresh();
    }           

}

private void Refresh()
{
    ICollectionView view = CollectionViewSource.GetDefaultView(employees);
    view.Refresh();
}          


private void lv_selectionChanged(object sender, SelectionChangedEventArgs e)
{ 
    var selectedEmployee = (Employee) lview.SelectedItem;
    if(selectedEmployee != null)
    {
        tb_firstname.Text = selectedEmployee.FirstName;
        tb_lastname.Text = selectedEmployee.LastName;
    }

}

XAML

<ListView ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Height="93" Name="lview" SelectionChanged="lv_selectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding FirstName}"></TextBlock>
                        <TextBlock Text="{Binding LastName}"></TextBlock>                            
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>

2 个答案:

答案 0 :(得分:1)

if (tb_firstname.Text != "")
{not empty code}

if (!string.empty(tb_firstname.Text))
{not empty code}

答案 1 :(得分:1)

您应该使用String.IsNullOrEmpty功能。您可以在MSDN上找到有关它的更多信息。

if (!String.IsNullOrEmpty(fname) && !String.IsNullOrEmpty(lname))
{
   ...
}