I'm very new to WPF and I have data binding down in winforms, but I'm about to pull my hair out here trying to simply bind a textbox, to a property.
I'm simply trying to bind my options classes to various controls, the one I'm currently trying to bind is AppCliOptions.CLIPath
I first just want to say I've been at this now for a few days now, spending an hour or so a day trying to figure out what is wrong. However I haven't found anything specific to what I'm trying to do, maybe I'm just overlooking it, or I still don't get WPF and xaml yet, I'm sure it's something simple.
I did see some saying you can't bind to a static class, but my classes aren't static, just my reference to the instance is.
I have a static singleton class, this is an example.
public abstract class AppOptionsBase<T> : INotifyPropertyChanged where T : AppOptionsBase<T>, new()
{
protected static T instance = new T();
public event PropertyChangedEventHandler PropertyChanged;
public static T Instance => instance;
protected AppOptionsBase() { }
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public class AppCliOptions : AppOptionsBase<AppCliOptions>
{
private string _cliPath;
public string CLIPath { get => _cliPath; set { _cliPath = value; OnPropertyChanged("CLIPath"); } }
public AppCliOptions()
{
//Set defaults
CLIPath = @"C:\Path\to\CLI.exe";
}
}
My Xaml.cs file
public static AppCliOptions CLIOptions => AppCliOptions.Instance;
My .xaml file
<TextBox Grid.Row="1" Grid.Column="0" DataContext="{Binding CLIOptions}" Text="{Binding Path=CLIPath}" BorderBrush="Black"/>
The textbox text is always blank, if I call the CLIOptions.CLIPath through code I get the default value as expected. After all the reading I've done I've tried dozens of different ways to try and bind to this, but I can't seem to get it to work.
I got it working by not trying to set the context in xaml.
Window loaded event
txtCLIPath.DataContext = CLIOptions;
XAML
<TextBox x:Name="txtCLIPath" Grid.Row="1" Grid.Column="0" Text="{Binding CLIPath}" BorderBrush="Black"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.