How to control DynamicResource implementation in C# - c#

In my program I would like to implement a DynamicResource from code-behind. Right now I am binding the Content of a Label to a string property in my Data Model...
<Label Content="{Binding DataModel.StringValue}" ... />
Following this question, I have implemented the string in my Data Model like so:
private string _stringValue = (string)Application.Current.Resources["nameOfResource"];
public string StringValue
{
get { return _cartsInSystem; }
set
{
_cartsInSystem = value;
NotifyPropertyChange(() => CartsInSystem);
}
}
I would like to make it so that every time the user changes the Resource Dictionary, this string value updates with the new value.
I am trying to achieve the same effect as something like this:
<Label Content="{DynamicResource nameOfResource}" ... />
Please let me know what I am doing wrong, and how I might correctly implement something like this.
UPDATE 1: As requested by #HighCore, this is an example of my code where I only have access to string values from code-Behind (or C# class)
(This is part of a ViewModel of a TreeView in my MainWindow)
//The "DisplayNames" for these nodes are created here and not accessible through xaml.
//This is because the xaml window has access to this code through it's itemsSource
private HierarchicalVM CreateCartsNode()
{
return new HierarchicalVM()
{
DisplayName = "Carts",
Children =
{
new CartConnection() { ConnectionDataModel = new CartConnectionModel(), DisplayName = "Cart Connection" },
new HierarchicalVM() {
DisplayName = "Cart Types",
Children = {
CreateCartType( new CartConfigModel() { DisplayName = "Default" }, new CartIO_Model() ),
},
Commands = { new Command(OpenAddCart) {DisplayName = "Add..."} }
}
}
};
}
This is the xaml of the above TreeView:
<!-- Tree view items & Functions -->
<TreeView ItemsSource="{Binding DataTree.Data}" ... />
Update 2: I have another perfect example of my problem...
I have a comboBox that has it's itemsSource bound to an ObservableCollection in my Data Model. Like so:
private ObservableCollection<string> _objCollection;
private string _notUsed = "Not Used";
private string _stop = "Stop";
private string _slow = "Slow";
public DataModel()
{
ObjCollection = new ObservableCollection<string>() { _notUsed, _stop, _slow };
}
public ObservableCollection<string> ObjCollection {...}
xaml:
<ComboBox ItemsSource="{Binding DataModel.ObjCollection}" ... />
If I want to make it so that the items in this comboBox change when the resource dictionary is changed, it looks like I'll need to handle it in C# rather than xaml.

After OP's UPDATE 2 and having a chat with him for a different question, I understood he was trying achieve localisation for his application. He would change Resource Dictionaries (for different languages) on the fly, and he wanted his C# code re-read/load values from Application.Current.Resources.
APPROACH ONE
After you changing the Resource Dictionary, You could use something like EventAggregator/Mediator to let other parts of the application (including ViewModels) know about Resource Dictionary change, and they respond to it by re-loading/reading resources/values from Application.Current.Resources
APPROACH TWO
OP doesn't want to introduce any new dependencies like EventAggregator/Mediator. So, I suggested this second approach. I know, it is not pretty, but here it goes..
You could have a global static event instead of EventAggregator/Mediaotr to let other parts of the application know that you swapped resource dictionary, and they will re-load/read values.
Read this answer about potential problems with static events and their subscriptions.

Related

Get TextBox name from WPF application with MVVM model in helper class

So I am trying to build a MVVM application with WPF and i am stuck with this problem:
In the view class, I have a list of textBoxes that I want to acces in order to validate the inputs.
So I managed to do this by writing in the view class, and it works:
var list = mainGrid.Children.OfType<TextBox>().ToList();
var dictOfTb = new Dictionary<string, string>();
foreach (var item in list)
{
dictOfTb.Add(item.Name, item.Text);
}
But the problem is that I am trying to respect the MVVM pattern and I should to this in a helper class, lets call it ModelsPageHelper, and access it from the View, because here what I am trying to do is to only get data from the UI and pass it to the viewModel to get a result, and then to display it.
So in this class I wrote a method,GetValuesFromTextBoxes(List<TextBox> textBoxes) and I am writing the same code, but now I get a message saying that TextBox does not contain a definition for Name.
So the question is, how can I do the same thing in the helper class to acces the names of those textBoxes?
To do MVVM properly you have to stop thinking about code to validate text boxes, and think about a ViewModel that validates itself, and a view that displays the state of the ViewModel.
For example, if you have a property called Foo which must have the value Bar, the code would look like this:
public string FooError { get; private set; }
private string foo;
public string Foo
{
get => return foo;
set
{
foo = value;
if (foo == "Bar") FooError = "";
else FooError = "Foo must be Bar";
NotifyPropertyChanged();
NotifyPropertyChanged(nameof(FooError));
}
}
and your XAML would look something like this:
<TextBox Text={Binding Foo}/>
<TextBlock Text={Binding FooError}/>
Then perhaps your save button could check for errors too.
I'd strongly advise you to look into INotifyDataErrorInfo, which is a great way to organise your errors in a way that WPF can easily display (instead of properties like FooError). It might seem like a lot of work the first time you use it, but it's great once you've got lots of controls and validation rules.

WPF/MVVM: Dynamically add checkboxes to 2 ColumnGrid based on available Enums

I'm currently build a gui for a logger. The logger class has a enum Types with a couple of values defining the different log message types.
Now I want to create a gui for this logger. Part of this gui is a 2 column grid where a checkbox for each log message type is available. It shall be used to filter the log. In order to reduce future coding effort, I would like to add a checkbox for each available type of log message dynamically. So when ever a new value is added to Logger.Types the gui adapts automatically.
My xaml of the checkboxes look something like this:
<CheckBox Name="CheckBoxTypeInformation" Grid.Column="0" Grid.Row="1"
Content="{myControls:LocalizationMarkup 'LOGMSG_TYPE_INFORMATION'}"
Command="{Binding FilterTypeCommand}" CommandParameter="Information"
IsChecked="{Binding Path=FilterType[0]}"/>
So there is quite some work to be done for each checkbox:
Insert the cb into the 2 column grid in some manner by defining the Grid.Column and Grid.Row. The logic of it is not the problem
Set the Content with a custom LocalizationMarkup
Bind a command with dynamic CommandParameter. Here I would like to pass the actual enum value. But I was not able to do so in xaml atm.
Bind the IsChecked Property to an index in an array holding the IsChecked Status of all checkboxes.
I'm not quite shure how to handle this. As I understood it correctly I somehow have to add an ObservableCollection<> of a new custom class which has properties for each of the 4 wanted tasks.
I hope somebody can point me into the right direction on how to implement something dynamic as described in a propper mvvm/wpf manner.
Thank you very much!
I would't use a grid for that, but simply a List.
Define a classe named LogLevelViewModel with two properties
private string _logDetails;
public string LogLevelDetails
{
get
{
return _logDetails;
}
set
{
if (_logDetails == value)
{
_logDetails = value;
RaisePropertyChanged(nameof(LogLevelDetails));
}
}
}
private LogLevel _logLevel;
public LogLevel LogLevel
{
get
{
return _logLevel;
}
set
{
if (_logLevel == value)
{
_logLevel = value;
RaisePropertyChanged(nameof(LogLevel));
}
}
}
Then define on your view model a ObservableCollection LogLevelViewModels
On the constructor of the view model, you can populate it With:
foreach (LogLevel level in Enum.GetValues(typeof(LogLevel )))
{
LogLevelViewModels.Add(level );
}
On the XAML make sure to define a DataTemplate for LogLevelViewModel and that's it.

C# WPF How can I have multiple DataContext

I am very new to WPF so despite finding other similar threads, my code is a little different so I don't know how to apply those solutions to mine.
<grid>
<CheckBox
x:Name="sortChk"
Content="Sort Variables"
IsChecked="{Binding SortVariables}"
/>
<b:FlatButton Command="{Binding ClickCommand}">
<TextBlock Text="Compare" FontSize="13"></TextBlock>
</b:FlatButton>
</grid>
Code behind looks something like this
string dataset1FullPath = null;
string dataset2FullPath = null;
string dataset1FilePath = null;
string dataset2FilePath = null;
public bool SortVariables { get; set; }
public SingleCompareWindow(string path1, string path2)
{
InitializeComponent();
dataset1FullPath = path1;
dataset2FullPath = path2;
dataset1FilePath = System.IO.Path.GetDirectoryName(path1);
dataset2FilePath = System.IO.Path.GetDirectoryName(path2);
//DataContext = this;
DataContext = new DataCompareVM(dataset1FullPath, dataset2FullPath, dataset1FilePath, dataset2FilePath, SortVariables);
}
You can see that I have commented out DataContext = this. If I dont comment it out and remove the other DataContext, then my SortVariables variable will take the value of the checkbox. If I have the other DataContext for the button click, then the checkbox will not bind. I need it to bind as I pass it as a parameter to DataCompareVM().
I'm very new to WPF and MVVM so forgive my ignorance.
You can't have more than one DataContext for a WPF control, you should move your properties to the ViewModel.
Yes, you can have different data contexts for different elements. But here you're trying to replace the same, window data context.
What you can do is use the named element. Replace your commented line with:
sortChk.DataContext = this;
Now, for the longest answer: you're not really doing MVVM here. As Fildor mentions, you should instead move the SortVariables property to the DataCompareVM ViewModel.
Since you seem to be struggling with MVVM, I believe reading my introductory book will help you get things straight: Learn WPF MVVM.

Multiple Views of Observable Collection with Datagrid

I have the same problem like this. But I´m using a DataGrid instead of a ListBox and it does not seem to work like this (it might also be because i never used visual basic and didnt translate the code correcly into c#).
I basicly want two DataGrids on the same data with different filters.
ICollectionView view_dataLinesUnfiltered;
ICollectionView view_dataLinesFiltered;
public MainWindow()
{
...
//view_dataLines = CollectionViewSource.GetDefaultView(dataLines); // <- Filter works on both
view_dataLinesUnfiltered = new CollectionView(dataLines); // <- Filter doesn´t work at all
view_dataLinesFiltered = new CollectionView(dataLines);
....
// Control Events
this.ShowAA.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ToggleButton.UncheckedEvent));
}
private void ShowAA_Checked(object sender, RoutedEventArgs e)
{
view_dataLinesUnfiltered.Filter = null;
}
private void ShowAA_UnChecked(object sender, RoutedEventArgs e)
{
view_dataLinesUnfiltered.Filter = delegate(object o) { return FilterContent(o as ErrorDetection.stDataLine, "AA", ""); };
}
bool FilterContent(ErrorDetection.stDataLine line, string sFilterAA, string sFilter)
{
shortArrayToHexStringConverter converter = new shortArrayToHexStringConverter();
string comBuffer = converter.Convert(line.ComBufferP as object,typeof(string),0,System.Globalization.CultureInfo.CurrentCulture) as string;
return false;// !comBuffer.Contains("AA");
}
The FilterContent method is being called without problems, but the DataGrid shows the lines anyway. If I use GetDefaultView the Filter works on both Datagrids. Do I have to use some other view instead of CollectionView (ListCollectionView does also not work)?
i have made a small sample project to show the problem sample. It only consists of an constructor and an observable collection.
I got it to work somehow. I used CollectionViewSources now instead of ICollectionView.
<Window.Resources>
<CollectionViewSource x:Key="viewSource_dataLinesUnfiltered"/>
<CollectionViewSource x:Key="viewSource_dataLinesFiltered"/>
</Window.Resources>
...
<DataGrid Name="Filtered_Datagrid" ItemsSource="{Binding Source={StaticResource viewSource_dataLinesFiltered}}" >
...
</DataGrid>
...
<DataGrid Name="Unfiltered_Datagrid" ItemsSource="{Binding Source={StaticResource viewSource_dataLinesUnfiltered}}">
...
</DataGrid>
and the c Code:
CollectionViewSource viewSource_dataLinesUnfiltered;
CollectionViewSource viewSource_dataLinesFiltered;
...
public MainWindow()
{
InitializeComponent();
this.DataContext = dataLines;
viewSource_dataLinesUnfiltered = (CollectionViewSource)this.Resources["viewSource_dataLinesUnfiltered"];
viewSource_dataLinesUnfiltered.Source = dataLines;
viewSource_dataLinesFiltered = (CollectionViewSource)this.Resources["viewSource_dataLinesFiltered"];
viewSource_dataLinesFiltered.Source = dataLines;
// Control Events
this.ShowAA.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ToggleButton.UncheckedEvent));
}
private void ShowAA_Checked(object sender, RoutedEventArgs e)
{
viewSource_dataLinesUnfiltered.View.Filter = null;
}
private void ShowAA_UnChecked(object sender, RoutedEventArgs e)
{
viewSource_dataLinesUnfiltered.View.Filter = delegate(object o) { return FilterContent(o as ErrorDetection.stDataLine, "AA", ""); };
}
bool FilterContent(ErrorDetection.stDataLine line, string sFilterAA, string sFilter)
{
shortArrayToHexStringConverter converter = new shortArrayToHexStringConverter();
string comBuffer = converter.Convert(line.ComBufferP as object,typeof(string),0,System.Globalization.CultureInfo.CurrentCulture) as string;
return !comBuffer.Contains("AA");
}
But I´m not sure why it works this way and the filter is not applied on window repaints when ICollectionView is used.
You need to specify which ICollectionVIew is used on which DataGrid.
If you just bind to the collection (dataLines in this case) WPF will use the 'default view' (or create one if necessary), this is why the first commented out line works for filtering.
There are a few ways you could specify which view is used for which datagrid, depending on what patterns, etc. you are using
1) Like the linked question, you could set the ItemsSource for each DataGrid in the window's code behind, after initializing the views, e.g.:
filteredDataGrid.ItemsSource = view_dataLinesFiltered;
unfilteredDataGrid.ItemsSource = view_dataLinesUnfiltered;
2) You could set the DataContext of the window to itself, or make a view model for the screen that contains the view, and make the views public properties and then bind to the intended view for each grid, e.g.
<DataGrid ItemsSource="{Binding View_dataLinesFiltered}"> ....
Edit:
Now I'm not at work and can get to dropbox and play with your example it seems like the cause of the weird behaviour is the use of CollectionView directly. On the msdn page for CollectionView it says
You should not create objects of this class in your code. To create a
collection view for a collection that only implements IEnumerable,
create a CollectionViewSource object, add your collection to the
Source property, and get the collection view from the View property.
However, if you don't want to set up the views in XAML, you could also change your CollectionViews to ListCollectionViews and it should work as expected (this is likely the view type that CollectionViewSource is making for you behind the scenes anyway).

Can't seem to get WPF DataBinding in my head

Ok, I'm no newbie at programming or C# as such, I just can't seem to get WPF's databinding straight in my head. My colleagues are raving about it (and yes, I will ask them as well) but right now I'm stumped.
Here's what I'd like to do for starters:
As an example I've got a list of things like this:
List<Thing> thingList = Source.getList();
Now normally I'd go
foreach(Thing t in thingList)
{
//add thing to combobox
}
But from what I can gather is that I can somehow not do this but use a databinding to populate the combobox for me.
What I can't seem to get is where do I put the 'thingList'? Do I make it a separate property somewhere? Where do I put that property?
I feel very stupid at the moment, as I've been struggling with this for a while now and I can't find any examples out there that make me understand this - probably very simple - concept.
Anyone out there willing to help me or point me at some step-by-step guide I might have missed?
Use ObservableCollection<T> for databinding in WPF. Where T is your class. See example below
public class NameList : ObservableCollection<PersonName>
{
public NameList() : base()
{
Add(new PersonName("A", "E"));
Add(new PersonName("B", "F"));
Add(new PersonName("C", "G"));
Add(new PersonName("D", "H"));
}
}
public class PersonName
{
private string firstName;
private string lastName;
public PersonName(string first, string last)
{
this.firstName = first;
this.lastName = last;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
Now in XAML. Go to resource tag
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
x:Class="Sample.Window1"
Width="400"
Height="280"
Title="MultiBinding Sample">
<Window.Resources>
<c:NameList x:Key="NameListData"/>
</Window.Resources>
<ListBox Width="200"
ItemsSource="{Binding Source={StaticResource NameListData}}" // Name list data is declared in resource
ItemTemplate="{StaticResource NameItemTemplate}"
IsSynchronizedWithCurrentItem="True"/>
xmnls:c will give you option to choose the class. Here you can choose c,d ,e x whatever but be sure it should be used earlier
When it comes to data-binding i've found that this page if read thoroughly answers most of the questions beginners have about it.
To answer the question: The alernative to adding all the items is to tell the ComboBox where to get its items from, this is done with the ItemsSource property.
You can either set this in XAML or in code, while you would need a binding expression in XAML a normal assignment should do in code:
comboBox.ItemsSource = thingList;
If you do not specify further how those objects in the list are to be displayed the ToString method will be called, unless overridden you will usually end up with the class-path of your object. There are two main ways of telling the application how to display the object:
The fist and more heavy option is Data Templates which is used for displaying complex data using controls (which in turn can have items and templates etc), the second way is using lightweight properties like DisplayMemberPath, which should be set to the name of the property which should be displayed (usually just a string).
If your list changes and the combo box should be updated on its own the source should implement INotifyCollectionChanged, in most cases you will use the standard implementation ObersableCollection<T>.
Most people would use WPF Databinding to populate the combobox but you don't have to.
You can add the items via code if you want to.
It's easy to get trapped into doing everything as it "should" be done without have a good reason for doing it that way (BTW, I'm not recommending you manually add the items, I'm just saying you can).
List<Thing> thingList = Source.getList();
foreach(Thing t in thingList)
{
combobox.Items.Add( t );
}

Categories