Menu
  • HOME
  • TAGS

Is there a way to raise PropertyChanged when binding to Model?

Tag: wpf,mvvm

In our WPF/MVVM application, we are binding to property of the Model directly because the Model is from legacy library (we added the support of INotifyPropertyChanged to the Model class). I.e., the code of ViewModel looks like

Public Class MyViewModel
    Inherits ViewModelBase

    Public Property Model As MyModel

End Class

And then the binding looks like this:

<TextBox Text="{Binding Model.Prop1}" />

Everyting worked fine until I have this requirement to have some properties in the ViewModel which depend on Model.Prop1. Specifically, I am binding the ItemSource of one ComboBox to a property of collection in the ViewModel, and this collection should be refreshed/recalculated whenever Model.Prop1 is changed. The code looks like this:

<ComboBox ItemsSource="{Binding MyCollection}" />

I have some options but they are not good in my opinion:

  1. I can have Model class hold a reference of ViewModel. And in the setter of Prop1 in the Model I update the MyColleciton property of ViewModel. Of course it is not a good idea
  2. Use EventAggregator for the communication between Model and ViewModel. Not efficient in my opinion plus I need to make big change in the Model class too.
  3. Let ViewModel have one property Prop1 and bind to this. In the getter of it return Model.Prop1 and in the setter assign ModelProp1 = Value. This is my current solution but there is one problem: in our Model we have other property/attribute which are useful and we create a common Style based on this property/attribute. For example, when the Model.Prop1 is changed, another property called IsDirty in Model class is set to True and in the View we change the color. But if we use Prop1 from ViewModel, instead of from Model, we lose this common Style behavior like other properties.

So now I still want to use the binding to {Binding Model.Prop1} (not create a wrapper property in the ViewModel) but somehow notify other properties in the Model when it is changed. Can I do that?

Best How To :

You said that we added the support of INotifyPropertyChanged to the Model class. Now if that means that you extended, or added to the original class and added calls to the INotifyPropertyChanged.PropertyChanged event from each property, then you can easily find out which property was changed using that event:

Model.PropertyChanged += Model_PropertyChanged;

Then in the PropertyChanged handler:

private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Prop1") 
    {
        // The Prop1 property value has changed
        RefreshYourCollection();
    }
}

However, if by we added the support of INotifyPropertyChanged to the Model class, you mean that your view model implements the INotifyPropertyChanged interface, then in reality, you have not added the support of the INotifyPropertyChanged interface to your Model class and you cannot do this.

If that is the case, then you will first need to implement the INotifyPropertyChanged interface correctly for each relevant property in the class. If you cannot change the original class, then you should extend it in a class that implements the INotifyPropertyChanged interface correctly and expose each property of the original class as new properties that notify the INotifyPropertyChanged interface correctly.

WPF Listbox Collection custom sort

wpf,sorting,listbox,compare,collectionview

You just have to check if it starts with "price". Note that I don't think that ToString() is appropriate; you should rather implement IComparer<T> and strongly type your objects in your listbox. public int Compare(object x, object y) { // test for equality if (x.ToString() == y.ToString()) { return 0;...

C# XAML - How to add a combobox to some datagrid ROWS but not others?

c#,wpf,xaml,datagrid,combobox

Try using a DataTrigger with predefined DataTemplate items: <DataTemplate x:Key="OneItem" DataType="{x:Type ValueItem}" > <TextBox Text="{TemplateBinding Id}" /> </DataTemplate> <DataTemplate x:Key="MultiItems" DataType="{x:Type ValueItem}" > <ComboBox ItemsSource="{TemplateBinding ValueItems}" DisplayMemberPath="ValueName" SelectedValuePath="ID" SelectedValue="{TemplateBinding Id}" /> </DataTemplate> And then use a Content control to place the style accordingly. I haven't tried this but your data...

Add image to the radio button

c#,wpf,xaml

This adds a picture to the background of your radio button. myRadioButton.Content = new Image() { Source = (new ImageSourceConverter()).ConvertFrom( "Images/pic.png") as ImageSource }; ...

ItemsSource bind to collection stays empty

c#,wpf,xaml,mvvm

In order to observe changes in a collection WPF provides the ObservableCollection class which implements INotifyCollectionChanged and INotifyPropertyChanged. Replace List<T> with ObservableCollection<T> and your code should work.

Microsoft Band and WPF

.net,wpf,dll,microsoft-band,.net-core

The current Band SDK does not support Windows desktop (i.e. Win32) applications. It supports only Windows Store and Windows Phone (i.e. WinRT) applications. Portable libraries can be confusing as the terms '.NETCore' and 'netcore451' refer to the Windows Store version of the .NET framework....

WPF, DataGrid, clicked item/row does not highlight (blue background)

c#,wpf,linq,datagrid

Here is the solution that works: private void tabControlOrganizer_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (tabControlOrganizer.SelectedItem != null) { if (e.Source is TabControl) { if (tabItemTrades.IsSelected) { dataGridTrades.ItemsSource = Queries.GetTradeList(dataContext); } SelectionChanged was the problem: In C# WPF, why is my TabControl's SelectionChanged event firing too often? In free time I...

Validate a field only if it is populated

c#,wpf,idataerrorinfo

You can implement your OptionalPhoneAttribute based on the original PhoneAttribute: public sealed class OptionalPhoneAttribute : ValidationAttribute { public override bool IsValid(object value) { var phone = new PhoneAttribute(); //return true when the value is null or empty //return original IsValid value only when value is not null or empty return...

Should I be using more than one viewmodel for a database table?

c#,wpf,mvvm

As usual the answer is ain't common, it depends on how you really want to implement it. But for the sake of patterns and organized code, i would recommend that you have: Separate Viewmodel per view: each viewmodel should only contain as many data as many you want to display/work...

Changing color of positionmarker/caret

wpf,wpfstyle

To modify the color of the caret (which assume is what you call "positionmarker") you have to set the CaretBrush property of the TextBox.

WPF: static INotifyPropertyChanged event

wpf,binding

Instead of a static counter you should have a view model with a collection of Person objects public class ViewModel { public ObservableCollection<Person> Persons { get; set; } } and bind the ItemsSource property of the ListView to this collection. <ListView ItemsSource="{Binding Persons}"> ... </ListView> You could now bind to...

WPF expander not expanded above buttons make buttons unclickable

wpf,xaml,clickable,expander

I found a way of doing it, with code behind. I put my Expander in a Canvas and I added to my Expander two events: Expanded="searchMenuExpander_Expanded" and Collapsed="searchMenuExpander_Collapsed" which are defined as: private void searchMenuExpander_Expanded(object sender, RoutedEventArgs e) { Canvas.SetZIndex(searchMenuCanvas, 99); } private void searchMenuExpander_Collapsed(object sender, RoutedEventArgs e) { Canvas.SetZIndex(searchMenuCanvas,...

Animation Methods, Simplification and Repairing

c#,wpf

Your issue is nothing to do with Animation.The problem is you are comparing sender.Type while you should compare sender itself i.e. use if (sender is TabItem) instead of if (obj is TabItem). Moreover, There is no need to compare sender with TabItem, Lable, Window and etc one by one, they...

Aligning StackPanel to top-center in Canvas

c#,wpf,xaml,canvas

If you don't want any input or hit testing on a certain element you should set the IsHitTestVisible property to false: <Grid> <Canvas Name="Canvas" Background="#EFECCA"> <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="{Binding ActualWidth, ElementName=Canvas}" Height="{Binding ActualHeight, ElementName=Canvas}" MouseLeftButtonDown="DockPanel_MouseLeftButtonDown" TouchDown="DockPanel_TouchDown" Panel.ZIndex="2" Background="Transparent"> </DockPanel> <Button Width="50" Height="50"...

Add stack panel when check box is checked

wpf,wpf-controls

What you can do is create the StackPanel in the xaml markup itself with the Visibility set to Collapsed and just toggle the visibility of the StackPanel on the check event of CheckBox

WPF style info from external text file

wpf,vb.net,styles

just hold the color values in a config file simple text file will suffice. though you can use VisualStudio Resource file.. file will contain lines in each: item_enum_name item_type item_value for example: main_screen_bg_color Color Black company_logo URI \logos\logo1.jpg and so on.. just load the file parse it and use bind...

How to draw something in DrawingVisual with millimeter unit instead of pixels?

c#,wpf,printing,drawingvisual

In WPF, you can't even draw something in pixel units without at least some extra effort. WPF uses "device independent units" where each unit is 1/96th of an inch. Even that is only a theoretical relationship, as it depends on the display device correctly reporting its resolution, which in turn...

Why BindingFlags are called so?

c#,wpf,reflection

Because the class that translates the metadata to a actual method is called Binder and BindingFlags are flags that are passed on to the binder to connect to the method.

WPF: 2 different label sizes in particular order alignment

wpf,alignment,label

To have such a result, your grid must be really small. I see at least 3 solutions to your issue: 1- Make your grid a bit bigger until it fits. 2- Put 2 columns in your grid, you'd put the number on the left column and the % on the...

Style vs inline property setting in silverlight with a custom control

c#,wpf,xaml,silverlight

That is not the correct way to register a dependency property. public bool UseCustomTooltips { get { return (bool)GetValue(UseCustomTooltipsProperty); } set { SetValue(UseCustomTooltipsProperty, value); } } public static readonly DependencyProperty UseCustomTooltipsProperty = DependencyProperty.Register("UseCustomTooltips", typeof(bool), typeof(MyControl), new PropertyMetadata(false, new PropertyChangedCallback(MyCallbackMethod))); Use the propdp snippet, it really is a beautiful thing....

MahApps - How to disable automatic uppercase of default button

wpf,mahapps.metro

You can override the default value by setting the property for all buttons in Window.Resources <controls:MetroWindow ... xmlns:controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Window.Resources> <ResourceDictionary> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="controls:ButtonHelper.PreserveTextCase"...

WPF maximize main window with center for application

c#,wpf,window

Set the WindowState property instead of Width and Height: mainWindow.WindowState = WindowState.Maximized; ...

Change Background image in WPF using C# [duplicate]

c#,wpf,image,background,resources

Firstly, add a Folder to your Solution (Right click -> Add -> Folder), name it something like "Resources" or something useful. Then, simply add your desired image to the folder (Right click on folder -> Add -> Existing item). Once it's been added, if you click on the image and...

TwoWay Binding is not working if Binding is changed from DataTrigger

wpf,datatemplate,datatrigger,2-way-object-databinding

Your answer can be found in the Dependency Property Value Precedence page on MSDN. In short, you have set a local value on the IsOpen property and that has a higher precedence than the value set by the Trigger. The solution is to not set the local value, but to...

CollectionView: Filter does not work when binding to e. g. ListBox

c#,wpf

The very first line in the remarks section of the documentation for the CollectionView class says: You should not create objects of this class in your code. So, I am guessing it is probably not designed to be used the way you are using it. I always use CollectionViewSource.GetDefaultView(collection) (which...

Binding string lists into wpf listview returns BindingExpression path error

c#,wpf,listview,data-binding

But you aren't binding a list of strings to a ListView, you are binding an IEnumerable<String> to a TextBlock.Text field, when it is expecting a String as you can see in the errors. The fastest way to solve your problem is to change the line to this.AInfoLv.Items.Add(new { Label=" "...

Get data from web pages and save locally

wpf,wpf-controls,html-parsing

As @goobering already mentioned, this is a very broad set of questions, I will attempt to guide you in the right direction here. How can I parse data from pages? I would recommend starting with RSS. Practically all news websites have some kind of RSS feed that you can tap...

WPF add new Slider style cause XamlParseException

wpf,slider,styles

These Styles reference other Styles and Templates via StaticResource: MyFocusVisualStyte (Typo? Shouldn't it be MyFocusVisualStyle?), SliderThumbStyle, SliderRepeatButtonStyle, HorizontalSlider, VerticalSlider... All these Styles and Templates must exist and be defined BEFORE they're used. In this case, the resources must be defined in this order (I'll copy only the first node of...

Viewmodel binding for Edit View

c#,entity-framework,mvvm

I believe you're on the right track with POST. GET is much more simplier: public ActionResult Create() { return View(new ContactsCreateViewModel() { ... your initial settings, may be contained within constructor of view model directly ... }); } The GET request requests server to provide empty form, which is filled...

finding file in root of wpf application

c#,xml,wpf,visual-studio,relative-path

First, ensure that the file is definitely copied into your output ./bin/ directory on compile: This worked perfectly for me in my WPF application: const string imagePath = @"pack://application:,,,/Test.txt"; StreamResourceInfo imageInfo = Application.GetResourceStream(new Uri(imagePath)); byte[] imageBytes = ReadFully(imageInfo.Stream); If you want to read it as binary (e.g. read an image...

TextBlock hosted inside StackPanel/Grid won't Wrap

wpf

StackPanel stretches accordingly to the size of its content. So if you use Grid and with TextWrapping you can achieve the desired result <Grid> <TextBlock TextWrapping="Wrap" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus leo lectus, viverra ut lobortis vel, mollis eget lectus. Suspendisse laoreet consequat ultrices. Curabitur ultricies,...

Adding table header to Listview with DataTemplate in XAML

c#,wpf,xaml,listview,windows-runtime

If you have to use ListView then this is how it works: <ListView Margin="120,30,0,120" ItemsSource="{Binding MainViewModel}" Grid.Row="1"> <ListView.View> <GridView> <GridViewColumn DisplayMemberBinding="{Binding Data, Mode=TwoWay}" Width="100" Header="Column 1" /> <GridViewColumn DisplayMemberBinding="{Binding Year, Mode=TwoWay}" Width="100" Header="Column 2" /> <GridViewColumn DisplayMemberBinding="{Binding Month, Mode=TwoWay}" Width="100" Header="Column 3" /> <GridViewColumn...

How do I provide a collection of elements to a custom attached property?

c#,wpf,binding

I managed to get it working using an IMultiValueConverter like this: public class BorderCollectionConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var borderCollection = new BorderCollection(); borderCollection.AddRange(values.OfType<Border>()); return borderCollection; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new...

C# Delete Row with Dynamic Textbox/Button/Grid

c#,wpf,button,dynamic,textbox

WPF's ItemsControl is the correct way to show items in your views when the number of items can change. Many controls inherit from ItemsControl, like the ComboBox itself, or the DataGrid, or the ListBox... But in this example I'll use ItemsControl directly, since what you're trying to do doesn't need...

How to print something in WPF without using controls? [closed]

c#,wpf,printing

You can utilize the utilize the PrintDocument class, which is not WPF specific. This class allows you to send output to a printer. The PrintPage event should be handled, where you utilize the PrintPageEventArgs to obtain a Graphics context; which is used to draw the exam to the printer output....

WPF custom button

wpf,button,styles

I'm going to attempt to answer your questions directly, however there is much that can be discussed here. What this template doing? All controls have some kind of default template, a pre-defined look and feel of what the control looks like. The Template is overriding the default look and feel...

Images aren't displayed in WPF ListBox

wpf,data-binding,listbox

The binding in the ListBox ItemTemplate should be to the ImageViewModel's ImageBinary property, instead of Images: <DataTemplate> <Border ...> <Image Source="{Binding ImageBinary}" .../> </Border> </DataTemplate> ...

CefSharp.Wpf WebView cannot accept input and the link clicked no response

wpf,chromium-embedded

Finally, I got the answer from https://github.com/cefsharp/CefSharp/issues/1080#issuecomment-111969127 I am sorry post the duplicate thread online. With the amaitland's help. I resolved this issue. We just needed remove OnMouseLeftButtonDown method. Thanks for your time....

WPF Navigation using MVVM

c#,.net,wpf,mvvm

The AncestorType should be MainWindow not MainViewModel. MainViewModel is not a class that is part of the visual tree.

ContentPresenter in ItemControl.ItemTemplate to show displaymemberpath of itemscontrol

c#,wpf,itemscontrol,contentpresenter

I found an easier way to solve this problem by using horizontal listbox. Thanks for responses

orderby () containing numbers and letters

c#,wpf,linq,linq-to-sql,sql-order-by

Given your example data where the first number is always a single digit: allScenes.OrderBy(x => x.SceneNumber).ToList() If you can possibly have multi-digit numbers, please provide them and where you want them in the sort order. This is one way to sort multiple digit numbers: var allScenes = new[]{ new {SceneNumber="4B"},...

WPF routedevent storyboard begin only if height is zero

wpf,storyboard,wpf-controls,routed-events

You may use a DoubleAnimation instead of an ObjectAnimationUsingKeyFrames. By only setting its To property, but not From, the animation starts from the current property value. It requires that you also set an initial value of the Height of the Border: <Border Height="20" ...> <Border.Triggers> <EventTrigger RoutedEvent="MouseLeftButtonUp"> <BeginStoryboard> <Storyboard> <DoubleAnimation...

System.Windows.Interactivity must be referenced in the main project

c#,wpf,dll,reference

System.Windows.Interactivity.dll is not in the GAC, so .Net doesn't know where to find it. By adding a reference to your main project, you make the build system copy the DLL to the output folder. This lets the runtime find it....

In WPF how can I control whether another button clicked

c#,wpf,button,mouseevent

if you want to use same Click handler for two button, try this: private void btnDashboard_Click(object sender, RoutedEventArgs e) { Button btnSender = sender as Button; if(btnSender.Name == "btn1") { //Code for Button1 } else { //Code for Button2 } } Also make sure each button has a Name property...

Custom WPF DataGrid with optional button column

c#,wpf,xaml,datagrid,custom-controls

I had to remove the section from the Generic.xaml style for the DataGrid to properly layout and created the column in code. protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); CloneColumn.Visibility = ShowCloneColumn ? Visibility.Visible : Visibility.Hidden; } private DataGridTemplateColumn _cloneColumn; private DataGridTemplateColumn CloneColumn { get { if (_cloneColumn == null)...

Images not appearing on WPF form when loading asynchronously

c#,wpf,multithreading,listbox,backgroundworker

@Clemens answer from his comment on the original question provided the solution. Ensuring that the file stream was being closed responsibly and changing the BitmapCacheOption to OnLoad now shows each image in the asynchronous load. The final code for the asynchronous load looks like: private void LoadAsync(object sender, DoWorkEventArgs e)...

How to access file from another function

c#,wpf,button

You can simply have a private variable outside of the Button_Click1 method which will hold the chosen file names. string[] files; private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Multiselect = true; dlg.FileName = "Document"; dlg.DefaultExt = ".txt"; dlg.Filter = "Text documents (.txt)|*.txt"; Nullable<bool>...

Open popup at the location of the button clicked

c#,wpf

You can use a Popup control, coupled with it's Placement property to display your popup based on the current location of your buttons. <Popup Placement="Top" PlacementTarget="{Binding ElementName=yourButton}" ... /> Inside your Popup, you can place your UserControl or any content element which will act as the popup's content. See here...