6

私は次のコードを持っています:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <TextBox Text="{Binding Path=Name, 
                            Mode=OneWayToSource, 
                            UpdateSourceTrigger=Explicit, 
                            FallbackValue=default text}" 
             KeyUp="TextBox_KeyUp" 
             x:Name="textBox1"/>
</Grid>

    public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            BindingExpression exp = this.textBox1.GetBindingExpression(TextBox.TextProperty);
            exp.UpdateSource();
        }
    }
}



    public class ViewModel
{
    public string Name
    {
        set
        {
            Debug.WriteLine("setting name: " + value);
        }
    }
}



    public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        Window1 window = new Window1();
        window.DataContext = new ViewModel();
        window.Show();
    }
}

テキストボックスで「Enter」キーが押されたときだけソースを更新したい。これはうまくいきます。ただし、バインディングはプログラムの起動時にソースを更新します。どうすればこれを回避できますか? 何か不足していますか?

4

2 に答える 2

-2

バインディングモードデフォルトに変更する

<TextBox Text="{Binding Path=Name, 
                    Mode=Default, 
                    UpdateSourceTrigger=Explicit, 
                    FallbackValue=default text}" 
        KeyUp="TextBox_KeyUp" 
        x:Name="textBox1"/>
于 2010-06-24T12:20:01.887 に答える