Reputation: 13
I wanna know how i can use Dynamic names in C#.
I have this, which adds a label to a Stackpanel with a Name.
SPLastChange.Children.Add(new Label() {Name = "gi" + GICount.ToString() +"lc" , Content = File.GetLastWriteTime(CSVPath + "Zentrale" + GICount.ToString() + ".csv").ToString(), Margin = new Thickness(0, 0, 0, 10), FontWeight = FontWeights.Bold, Height = 27 });
If i now try to assing a new Value to that Label, I fail
(FindName("gi" + GICount.ToString() + "lc") as Label).Content = "test";
It seems not to find the Name, but why?
EDIT
Even a Static name is not working, so the Variable has nothing to do with it.
Upvotes: 1
Views: 219
Reputation: 28988
The FrameworkElement.Name
must be registered with the current XAML namescope. Otherwise the name can not be found by the framework e.g., when using FrameworkElement.FindName
. Element names are always looked up by searching in the framewrok element's XAML namescope.
You must use FrameworkElement.RegisterName
e.g., of your MainWindow
:
MainWindow.xaml.cs
partial class MainWindow : Window
{
public void RegisterName()
{
var label = new Label() {Name = "MyLabel"};
RegisterName(label.Name, label);
}
}
But as suggested in the comments, don't create controls and add them to a panel in code-behind the way you are currently doing it. Instead use the ItemsControl
to create controls of a kind dynamically.
See Data binding overview in WPF, Data Templating Overview
LabelModel.cs
The model class. Instead of creating Label
control, you create this model. The actual Label
is created automatically by the ListBox
by applying the item template.
// All binding source models must implement INotifyPropertyChanged
public class LabelModel : INotifyPropertyChanged
{
private string lastWriteTime;
public string LastWriteTime
{
get => this.lastWriteTime;
set
{
this.lastWriteTime = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainWindow.xaml.cs
partial class MainWindow : Window
{
public ObservableCollection<LabelModel> LabelModels { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void AddLabel()
{
string labelContent = File.GetLastWriteTime(CSVPath + "Zentrale" + GICount.ToString() + ".csv").ToString();
var label = new LabelModel() { LastWriteTime = labelContent };
this.LabelModels.Add(label);
}
}
MainWindow.xaml
Upvotes: 1