[英]Bind button content to a variable
我在XAML中有以下內容:
<Button Content="{Binding KB.Text}" />
KB是以下類的實例:
public class ButtonText
{
public string Text
{
get
{
return "Button";
}
}
}
我在頁面后面的代碼中將KB定義為全局變量,在運行項目時按鈕內容顯示為空,我將如何實現此目的? 按鈕內容應由KB.Text檢索
確保初始化“KB”對象(不為null)。
您可能在主函數中錯過了“this.DataContext = this”
確保您的KB是屬性
這對我有用:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
KB = new ButtonText();
}
public ButtonText KB { get; }
}
public class ButtonText
{
public string Text
{
get
{
return "Button";
}
}
}
編輯:我寫了第一個解決WPF的解決方案,花了一些時間來確定是否有“UWP”標簽。
在UWP中,如果要將某些內容綁定到設計器本身的代碼(* xaml.cs),則應使用“x:Bind”而不是“Binding”。
簡而言之,您的xaml應如下所示:
<Button Content="{x:Bind KB.Text}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.