基本上,我想在我的 c# 中將我的 xaml 中的文本框與變數 DisplayNumFilter 系結。我想將我的文本框初始化為 20。我一直在查看幾個堆疊溢位帖子并嘗試了很多東西,這是建構式有點亂(我嘗試了很多東西,只是把它們留在那里)。但是,沒有任何效果。對于格式或術語方面的任何錯誤,我深表歉意,我對此仍然很陌生。
這是我的 xaml 的片段:
<TextBox Name = "NumAccounts"
Text="{Binding Path = DisplayNumFilter, Mode=TwoWay}" />
這是我的 c# 代碼片段:
private string _displayNumFilter;
public string DisplayNumFilter{
get => _displayNimFilter;
set{
_displayNumFilter = value;
OnPropertyChanged("DisplayNumFilter");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName){
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public constructor(){ //it has a different name, I just use this as an example
DisplayNumFilter = "20";
InitializeComponent();
Binding binding = new Binding();
binding.Path = new PropertyPath("DisplayNumFilter");
binding.Source = NumAccounts;
BindingOperations.SetBinding(NumAccounts, TextBox.TextPoperty, binding);
NumAccounts.Text = DisplayNumFilter;
}
uj5u.com熱心網友回復:
XAML 標記Text="{Binding Path=DisplayNumFilter}"嘗試系結到DisplayNumFilter當前控制元件DataContext的a ,TextBox因此您需要將 設定為定義DataContext的類的實體。DisplayNumFilter
這意味著您的建構式應如下所示:
public constructor() {
DisplayNumFilter = "20";
InitializeComponent();
DataContext = this;
}
Binding如果您在 XAML 標記中使用設定系結,則沒有理由以編程方式創建物件。
uj5u.com熱心網友回復:
您的代碼存在一些問題,但我將重點關注主要問題:
您的系結源錯誤。從系結源開始,它將以屬性路徑開始。要決議屬性DisplayNumFilter,必須將源設定為this.
public SomeWindow()
{
DisplayNumFilter = "20";
InitializeComponent();
Binding binding = new Binding();
binding.Path = new PropertyPath("DisplayNumFilter");
binding.Source = this; // -> was before NumAccounts;
BindingOperations.SetBinding(NumAccounts, TextBox.TextPoperty, binding);
NumAccounts.Text = DisplayNumFilter;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446094.html
