【问题标题】:Making a WPF TextBox binding fire on each new character?在每个新字符上触发 WPF TextBox 绑定?
【发布时间】:2012-05-24 01:52:27
【问题描述】:

如何在 TextBox 中输入新字符后立即更新数据绑定?

我正在学习 WPF 中的绑定,现在我陷入了一个(希望如此)简单的问题。

我有一个简单的 FileLister 类,您可以在其中设置 Path 属性,然后当您访问 FileNames 属性时它会为您提供文件列表。 这是那个类:

class FileLister:INotifyPropertyChanged {
    private string _path = "";

    public string Path {
        get {
            return _path;
        }
        set {
            if (_path.Equals(value)) return;
            _path = value;
            OnPropertyChanged("Path");
            OnPropertyChanged("FileNames");
        }
    }

    public List<String> FileNames {
        get {
            return getListing(Path);
        }
    }

    private List<string> getListing(string path) {
        DirectoryInfo dir = new DirectoryInfo(path);
        List<string> result = new List<string>();
        if (!dir.Exists) return result;
        foreach (FileInfo fi in dir.GetFiles()) {
            result.Add(fi.Name);
        }
        return result;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string property) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(property));
        }
    }
}

我在这个非常简单的应用程序中使用 FileLister 作为静态资源:

<Window x:Class="WpfTest4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfTest4"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:FileLister x:Key="fileLister" Path="d:\temp" />
    </Window.Resources>
    <Grid>
        <TextBox Text="{Binding Source={StaticResource fileLister}, Path=Path, Mode=TwoWay}"
        Height="25" Margin="12,12,12,0" VerticalAlignment="Top" />
        <ListBox Margin="12,43,12,12" Name="listBox1" ItemsSource="{Binding Source={StaticResource ResourceKey=fileLister}, Path=FileNames}"/>
    </Grid>
</Window>

绑定正在工作。如果我更改文本框中的值,然后单击它外部,列表框内容将更新(只要路径存在)。

问题是我想在输入新字符后立即更新,而不是等到文本框失去焦点。

我该怎么做? 有没有办法直接在 xaml 中执行此操作,还是我必须处理框上的 TextChanged 或 TextInput 事件?

【问题讨论】:

    标签: c# wpf xaml data-binding textbox


    【解决方案1】:

    在您的文本框绑定中,您只需设置UpdateSourceTrigger=PropertyChanged。

    【讨论】:

    • 谢谢!就像我希望的那样简单的解决方案:)
    • 对我来说它不起作用...我想让文本恢复到以前的值,以防它不是数字。仅当添加 IsAsync=True 时才有效。
    • 我尝试在 Visual Studio 设计器 (VS2015) 中进行设置。在绑定对话框中,当我展开“更多设置”扩展器时会显示该选项。但是,除非我还将 BindingDirection 设置为 Default 以外的其他值,否则 UpdateSourceTrigger 被禁用。
    【解决方案2】:

    您必须将UpdateSourceTrigger 属性设置为PropertyChanged

    <TextBox Text="{Binding Source={StaticResource fileLister}, Path=Path, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
             Height="25" Margin="12,12,12,0" VerticalAlignment="Top"/>
    

    【讨论】:

      【解决方案3】:

      如果没有 C#,在 XAML 中对于 TextBox 就足够了,而不是对于类。因此,监控TextBlock的属性,其中TextBox的写入长度: 绑定文本长度

      <StackPanel>
        <TextBox x:Name="textbox_myText" Text="123" />
        <TextBlock x:Name="tblok_result" Text="{Binding Text.Length, ElementName=textbox_myText}"/>
      </StackPanel>
      

      【讨论】:

        【解决方案4】:

        滑块和关联文本框之间的数据绑定突然出现问题。 最后我找到了原因并可以解决它。 我使用的转换器:

        using System;
        using System.Globalization;
        using System.Windows.Data;
        using System.Threading;
        
        namespace SiderExampleVerticalV2
        {
            internal class FixCulture
            {
                internal static System.Globalization.NumberFormatInfo currcult
                        = Thread.CurrentThread.CurrentCulture.NumberFormat;
        
                internal static NumberFormatInfo nfi = new NumberFormatInfo()
                {
                    /*because manual edit properties are not treated right*/
                    NumberDecimalDigits = 1,
                    NumberDecimalSeparator = currcult.NumberDecimalSeparator,
                    NumberGroupSeparator = currcult.NumberGroupSeparator
                };
            }
        
            public class ToOneDecimalConverter : IValueConverter
            {
                public object Convert(object value,
                    Type targetType, object parameter, CultureInfo culture)
                {
                    double w = (double)value;
                    double r = Math.Round(w, 1);
                    string s = r.ToString("N", FixCulture.nfi);
                    return (s as String);
                }
        
                public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
                {
                    string s = (string)value;
                    double w;
                    try
                    {
                        w = System.Convert.ToDouble(s, FixCulture.currcult);
                    }
                    catch
                    {
                        return null;
                    }
                    return w;
                }
            }
        }
        

        在 XAML 中

        <Window.Resources>
            <local:ToOneDecimalConverter x:Key="ToOneDecimalConverter"/>
        </Window.Resources>
        

        进一步定义TextBox

        <TextBox x:Name="TextSlidVolume"
            Text="{Binding ElementName=SlidVolume, Path=Value,
                Converter={StaticResource ToOneDecimalConverter},Mode=TwoWay}"
        />
        

        【讨论】:

        • 我认为您在错误的问题中发布了答案。原始问题不包含有关滑块的任何信息。
        猜你喜欢
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 2015-05-22
        • 1970-01-01
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2018-03-18
        相关资源
        最近更新 更多