[英]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.我想用资源(两种方式)绑定 WPF 文本框,并且我想在我的代码中访问这个变量。
Here is my xaml code :这是我的 xaml 代码:
<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 :这是我的 C# 代码:
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
).您的TextBox
未绑定到任何DataContext
(而是绑定到StaticResource
)。 You should bind to a property of a self defined class used as DataContext
.您应该绑定到用作DataContext
的自定义类的属性。 You can set the DataContext
in the code behind.您可以在后面的代码中设置DataContext
。
Init of window:窗口初始化:
this.DataContext = new MyModel();
Anwhere in your code behind:在您的代码后面的某个地方:
MessageBox.Show(DataContext.MyPattern);
In your Xaml:在您的 Xaml 中:
<TextBox Text={Binding MyPattern}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.