简体   繁体   中英

WPF : How to bind textbox with resource in 2 ways?

I would like to bind WPF Textbox with resource (two ways) and I would like access to this variable in my code.

Here is my xaml code :

<Window.Resources>
    <system:String x:Key="SearchPattern">Eric</system:String>
</Window.Resources>
<TextBox Name="TxbRecherche" Margin="20,0" Text="{StaticResource SearchPattern }" >
    <TextBox.InputBindings>
        <KeyBinding Gesture="Enter" Command="{Binding BtnRechercher_OnClickechercher_Click}"/>
    </TextBox.InputBindings>
</TextBox>

Here is my c# code :

private void BtnRechercher_OnClickechercher_Click(object sender, RoutedEventArgs e)
    {
        string searchPattern = this.Resources["SearchPattern"].ToString();
        TbxStatus.Text = " Recherche de '" + searchPattern + "' en cours ...";

        //Lancement de la fenêtre de chargement dans un autre thread..
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

        if (bw.IsBusy != true)
        {
            pbRechercheEnCours.Visibility = Visibility.Visible;
            lblRechercheEnCours.Visibility = Visibility.Visible;
            bw.RunWorkerAsync(searchPattern);
        }
    }

What is missing ?

Your TextBox is not bound to any DataContext (instead it is bound to a StaticResource ). You should bind to a property of a self defined class used as DataContext . You can set the DataContext in the code behind.

Init of window:

this.DataContext = new MyModel();

Anwhere in your code behind:

MessageBox.Show(DataContext.MyPattern);

In your Xaml:

<TextBox Text={Binding MyPattern}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM