[英]WPF : How to bind textbox with resource in 2 ways?
我想用資源(兩種方式)綁定 WPF 文本框,並且我想在我的代碼中訪問這個變量。
這是我的 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>
這是我的 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);
}
}
有什么不見了 ?
您的TextBox
未綁定到任何DataContext
(而是綁定到StaticResource
)。 您應該綁定到用作DataContext
的自定義類的屬性。 您可以在后面的代碼中設置DataContext
。
窗口初始化:
this.DataContext = new MyModel();
在您的代碼后面的某個地方:
MessageBox.Show(DataContext.MyPattern);
在您的 Xaml 中:
<TextBox Text={Binding MyPattern}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.