wpf,binding , WPF: static INotifyPropertyChanged event


WPF: static INotifyPropertyChanged event

Question:

Tag: wpf,binding

This is my model:

class Person : INotifyPropertyChanged
{
    public static int Counter;
    public string _firstName;
    public string _lastName;
    public event PropertyChangedEventHandler PropertyChanged;

   public string FirstName
   {
        get {return _firstname; }
        set
        {
            _fileName = value;
            NotifyPropertyChange("FirstName");                
        }
   }

   public AddPerson(Person person)
   {
       Counter++;
   }
}

I have this NotifyPropertyChange that changed all my Persons properties inside my ListView and i want to add the Counter field that hold the number of Objects that i have. So is it possible to add another PropertyChanged Event for my static variable ?


Answer:

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 the Count property of the collection to get the number of elements:

<TextBlock Text="{Binding Persons.Count}"/>

For further reading see the Binding to Collections section in the Data Binding Overview article on MSDN.


Related:


Aligning StackPanel to top-center in Canvas


c#,wpf,xaml,canvas
I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

TextBlock hosted inside StackPanel/Grid won't Wrap


wpf
How do I make TexBox with an extremely long text wrap when it's placed inside StackPanel/Grid?

Add stack panel when check box is checked


wpf,wpf-controls
I want to add stack panel dynamically when check box is checked and if check box is unchecked then i want to remove that stack panel. I tried following code. when i run the program and check the check box nothing is happening. private void bCheckbox_Checked(object sender, RoutedEventArgs e) {...

Adding table header to Listview with DataTemplate in XAML


c#,wpf,xaml,listview,windows-runtime
In my Xaml I'm binding some data from a wcf. I don't know how to add some table headers to the columns. Also the data in the columns is not well aligned, I'm thinking it's because of the ColumnDefinition Width="auto". I want the columns to be aligned like in the...

Open popup at the location of the button clicked


c#,wpf
I am trying to create a popup that opens similar to the window preview option in Windows 8 taskbar. Basically, when I click or hover on a button, it opens a popup with basic information just above the button. Here is an example. Right now, I am able to open...

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


c#,wpf,mvvm
Bit of confusion, which I'm sure can easily be cleared up :). Lets say we have a table called "Contacts". The "Index" view for this table would be a datatable, listing all contacts in the table with First name, email and phone. Now, this would have a viewmodel containing Firstname,...

WPF: 2 different label sizes in particular order alignment


wpf,alignment,label
Please take a look at this picture: I try to create same label with 2 sizes: <Grid> <Label Content="11" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="50" /> <Label Content="%" HorizontalAlignment="Right" FontSize="20" VerticalAlignment="Top"/> </Grid> But currently this is not like the picture: ...

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


c#,wpf,linq,datagrid
Here is the DataGrid XAML: <DataGrid CanUserAddRows="False" AutoGenerateColumns="False" Height="501" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridTrades" VerticalAlignment="Top" Width="574" SelectionChanged="dataGridTrades_SelectionChanged"> <DataGrid.Columns> <DataGridTextColumn Header="ID" Binding="{Binding TradeID}" IsReadOnly="true"/> <DataGridTextColumn Header="Account" Binding="{Binding AccountName}" IsReadOnly="true"/> <DataGridTextColumn Header="Card Name" Binding="{Binding...

WPF add new Slider style cause XamlParseException


wpf,slider,styles
i found this slider style that i want to add. i added all the 3 styles inside my Window.Resources and also put in the first style the 2 templates: <Style TargetType="{x:Type Slider}"> <Setter Property="FocusVisualStyle" Value="{StaticResource MyFocusVisualStyte}" /> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type...

WPF 'Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.'


c#,wpf,nuget,mahapps.metro
My application runs fine in VS 2010 but when I copy the executable from the bin folder to another location I get this error: 'Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.' Line number '15' and line position '23'. Did a bit of testing and found out that if I include the...

WPF: static INotifyPropertyChanged event


wpf,binding
This is my model: class Person : INotifyPropertyChanged { public static int Counter; public string _firstName; public string _lastName; public event PropertyChangedEventHandler PropertyChanged; public string FirstName { get {return _firstname; } set { _fileName = value; NotifyPropertyChange("FirstName"); } } public AddPerson(Person person) { Counter++; } } I have this NotifyPropertyChange...

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


c#,wpf,binding
I found a few examples online, and a few questions and answers here, but I just can't get it to work. I need a custom attached property that can take one or more target elements. For example... <ListView> <dd:MyDragDrop.DropBorders> <Binding ElementName="brdOne"/> <Binding ElementName="brdTwo"/> <Binding ElementName="brdThree"/> </dd:MyDragDrop.DropBorders> </ListView> I've also had...

MahApps - How to disable automatic uppercase of default button


wpf,mahapps.metro
I have started to introduce MahApps.Metro (really awesome) in my WPF application and my favorite button is the default. The problem is that it puts all my text in uppercase and I don't want it.

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


c#,wpf,dll,reference
So I have a WPF project and my interface in a different project than the main one. I went to reference System.Windows.Interactivity, but it would not work. Not until I added it as a reference to the main project as well... This is the first time this has ever happened...

Get data from web pages and save locally


wpf,wpf-controls,html-parsing
I start to learn WPF and there is something that is still unclear for me: I want to create app, which can get information from online web sites (e.i. news). How can I parse data from pages? And second question, which is connected first one, How can I save user...

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


c#,wpf,xaml,datagrid,combobox
I'm using a key/value observable collection to hold data which is represented in the view by a two column datagrid. Some key values contain a list of items and other key values contain a single string value. Using the below code snippet I'm able to display those key values with...

WPF expander not expanded above buttons make buttons unclickable


wpf,xaml,clickable,expander
In a WPF form, I have an expander that expands above other controls, such as buttons : <Expander Grid.Row="0" Panel.ZIndex="99" Name="searchMenuExpander" Header="Search menu" FontWeight="Bold" HorizontalAlignment="Stretch" Margin="10,10,0,0" MinWidth="510" MinHeight="200" VerticalAlignment="Top" Foreground="MidnightBlue" Cursor="Arrow"> <Grid Background="White"> <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> <TextBlock Text="Name" HorizontalAlignment="Left" VerticalAlignment="Top"...

C# Delete Row with Dynamic Textbox/Button/Grid


c#,wpf,button,dynamic,textbox
I've tested some thinks with Dynamic Textboxes and Buttons, Adding Items to my Grid works very well, but if I want to Delete it there are some Bugs, sometimes 1 Row is empty and my Add Button disappears or my Program crashs. What did I wrong or what did I...

Animation Methods, Simplification and Repairing


c#,wpf
Context I'm kinda new at animating WPF stuff, but I've played around with a library or two and I "had" an animation that I used with the Window control in WPF, this is an example of that method, keep in mind that this method works: public void AnimateFadeWindow(object sender, double...

tool tip content change getting applied to all elements


wpf,tooltip,gridsplitter
I am creating an application in which I am creating grid splitters dynamically and applying style in the code. The style also sets the tooltip for these gridsplitters. I am using tool tip to display the width of controls and dynamically updating them when resized. When i am changing content...

Change Background image in WPF using C# [duplicate]


c#,wpf,image,background,resources
This question already has an answer here: Change WPF window background image in C# code 3 answers I'd like to change the background image of my WPF application by a button. I know how to do it using WindowsForms, but in WPF I failed. I found a solution already,...

Style vs inline property setting in silverlight with a custom control


c#,wpf,xaml,silverlight
I have a custom silverlight control that is pretty much a glorified text box. I have some properties in it I need to be able to set from the XAML in silverlight, so for each property I have created something like this: public bool UseCustomTooltips { get { return _useCustomTooltips;...

WPF maximize main window with center for application


c#,wpf,window
i have WPF application and i want to maximize main window. i tried the below code but the issue is that the window is maximized but not centered. i want the window to be maximized as i maximize window with mouse click. my code is: mainWindow.Height = SystemParameters.MaximizedPrimaryScreenHeight; mainWindow.Width =...

Why BindingFlags are called so?


c#,wpf,reflection
Coming from WPF background,just wondering, why BindingFlags in Reflection are called so? What is so "binding" about it?

Custom WPF DataGrid with optional button column


c#,wpf,xaml,datagrid,custom-controls
I am creating a custom DataGrid control which has a property, ShowCloneColumn. If you set this property to true the DataGrid should add another column with a Button. The class I've created derives from DataGrid and implemented a Dependency Property, ShowCloneColumn. public static readonly DependencyProperty ShowCloneColumnProperty = DependencyProperty.Register("ShowCloneColumn", typeof(bool), typeof(CloneRowDataGrid),...

WPF Navigation using MVVM


c#,.net,wpf,mvvm
I'm trying to follow the answer provided in this post, but I must be missing something trivial. I've defined my DataTemplates as App.xaml as follows: <Application.Resources> <DataTemplate DataType="{x:Type vm:BlowerViewModel}"> <v:BlowerView /> </DataTemplate> <DataTemplate DataType="{x:Type vm:HomeViewModel}"> <v:HomeView /> </DataTemplate> </Application.Resources> Then, in my MainWindow.xaml I've defined the following code: <Window x:Class="App.MainWindow"...

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


wpf,chromium-embedded
I used CefSharp.Wpf in my application. version: 1.25.7. I hosted the webpage via CefSharp WebView. I can host my webpage in it. But the TextBox in the WebView cannot accept the input, and the hyperlink cannot response. Here is my code. I created a Wpf Usercontrol named WebPageOemViewer. Xaml: <UserControl...

orderby () containing numbers and letters


c#,wpf,linq,linq-to-sql,sql-order-by
I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. This is the list I have 4B 1A 1 1B 2 4C 4 and want them to order like this where numbers are ascending followed by...

Binding string lists into wpf listview returns BindingExpression path error


c#,wpf,listview,data-binding
I've two string lists declared as below: Config.cs: public class AgentSkills { public List<string> agentSkillsNameList=new List<string>(); public List<string> agentSkillsLvlList=new List<string>(); } I retrieved the strings from an XML and added them to the lists as below: Config.cs: foreach (XmlNode skillNameNode in skillNameNodeList) { agentSkills.agentSkillsNameList.Add(skillNameNode.Attributes["value"].Value); } foreach (XmlNode skillLevelNode in skillLevelNodeList)...

Microsoft Band and WPF


.net,wpf,dll,microsoft-band,.net-core
I have downloaded the sample code for Band SDK for Windows. Then I added a new WPF project and grabbed the latest SDK through Nuget (Version 1.3.10518.1). Now under packages\Microsoft.Band.1.3.10518\lib, the following folders are contained: netcore451 portable-net45+win+wpa81 portable-win81+wpa81 wpa81 Now as I need .NET 4.5 support I have referenced the...

ContentPresenter in ItemControl.ItemTemplate to show displaymemberpath of itemscontrol


c#,wpf,itemscontrol,contentpresenter
I want to know is there anyway to put contentpresenter in itemtemplate of an itemscontrol to display my data. I don't want hard code binding like Text="{Binding username}" cause I am building a custom control, I think ContentPresenter is what I want. But after I tried using contentpresenter, it give...

Images aren't displayed in WPF ListBox


wpf,data-binding,listbox
I'm trying to display images in a ListView. The images are being loaded through Entity Framework from a SQL Server database. Somehow the images don't get displayed in the ListView and I can't figure out why. I've created a test Visual Studio project. The images are stored in an ObservableCollection<ImageViewModel>:...

WPF custom button


wpf,button,styles
I start to learn WPF and there is something that is still unclear for me: i created new Style for button: <!-- no border button style --> <Style x:Key="NoBorderButton" TargetType="Button"> <Setter Property="Foreground" Value="White" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Transparent" /> <Setter Property="BorderThickness" Value="0" /> <Style.Triggers> <Trigger Property="Control.IsMouseOver" Value="true">...

TwoWay Binding is not working if Binding is changed from DataTrigger


wpf,datatemplate,datatrigger,2-way-object-databinding
I have the following DataTemplate for my Tool Bar Items: <DataTemplate DataType="{x:Type viewModels:PopupContextActionViewModel}"> <Grid> <ToggleButton Name="ToggleButton"> <ContentControl Template="{Binding Icon, Converter={StaticResource NameToResourceConverter}}" Margin="5" /> </ToggleButton> <Popup Name="ContextActionPopup" StaysOpen="False" AllowsTransparency="True" IsOpen="{Binding ElementName=ToggleButton, Path=IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> <Border...

WPF style info from external text file


wpf,vb.net,styles
Not sure if this is possible, but I have a WPF application that now has a requirement to be skinnable. Basically, this equates to several key colours and a couple of logos. Is there any way of grabbing the hex values for the colours in defined styles from an external...

ItemsSource bind to collection stays empty


c#,wpf,xaml,mvvm
I have a class YouTubeVideo which contains some variables, which I would like to show on the UI. Therefore I created a custom control which shows all the data of the class. There are more than one instances of the class, so I would like to use an ItemsControl to...

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


c#,wpf,printing,drawingvisual
I'm trying to draw something in a System.Windows.Media.DrawingVisual but I need to draw thins in millimeter unit. How can I do that?

WPF routedevent storyboard begin only if height is zero


wpf,storyboard,wpf-controls,routed-events
I have the following XAML for a border trigger that uses a routed event <Border.Triggers> <EventTrigger RoutedEvent="MouseLeftButtonUp" EnterActions=""> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames BeginTime="0" Duration="0:0:0.4" Storyboard.Target="{Binding ElementName=messageWriterDefinition}" Storyboard.TargetProperty="Height"> <DiscreteObjectKeyFrame > <DiscreteObjectKeyFrame.Value> <GridLength>20</GridLength> </DiscreteObjectKeyFrame.Value>...

Add image to the radio button


c#,wpf,xaml
<StackPanel Name="StpAddDel" Orientation="Horizontal" HorizontalAlignment="Right" Margin="5"> <RadioButton Name="rdbactive" Content="Active" GroupName="actinact" VerticalAlignment="Center" Margin="5,0" Width="50" Height="15" Foreground="Blue"/> <RadioButton Name="rdbinactive" Content="InActive" GroupName="actinact" VerticalAlignment="Center" Margin="5,0" Width="60" Height="15" Foreground="Blue"/> <Button Name="BtnAdd" Height="20" Width="20" Margin="5,0" Template="{StaticResource AddImgBtnTemplate}" />...

finding file in root of wpf application


c#,xml,wpf,visual-studio,relative-path
I'm trying to load a file with pack://application: The file is situated in the root of my project but I keep getting a null reference error. However When I do an absolute reference it finds the file and loads just fine. What am I missing here? This doesn't work var...

WPF Listbox Collection custom sort


wpf,sorting,listbox,compare,collectionview
I have a listbox DropPrice MyPrice Price1 Price2 I want to sort it like this Price1 Price2 DropPrice MyPrice I mean, if there's an item that starts with the sequence "price", it gets priority, else the smallest string should get the priority. My source code: var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource)); var...

How to access file from another function


c#,wpf,button
I'm currently working on a C# WPF application which looks something like the following. What I am trying to do is this, the first button, when pressed, basically opens up a browse dialog box where you can select multiple files. I want access to those paths inside my other button...

Images not appearing on WPF form when loading asynchronously


c#,wpf,multithreading,listbox,backgroundworker
I'm attempting to display (in a ListBox with a custom DataTemplate) a series of BitmapSource frames (thumbnails) extracted from a multi-page tiff image. When I process the tiff on the UI thread, and either directly add the images to a listbox's item collection or add them to a bound ObservableCollection,...

In WPF how can I control whether another button clicked


c#,wpf,button,mouseevent
I want to determine another button is clicked in wpf. I wrote same code as below, when I clicked that button the animation works after that when I clicked same button the animation work like as else block. But I want to control if another button is clicked and than...

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


c#,wpf,printing
I'm newbie in WPF and I'm trying to print student's exam papers using WPF and I'm creating exam papers using System.Drawing.Graphics and now I want to print them. But it seems every printable thing in WPF is somehow a control. I have two problems: I don't know how can I...

Changing color of positionmarker/caret


wpf,wpfstyle
What is the name of the element of a text box control which I need to manipulate to achieve a change of the color of the position marker in the text box? The normal foreground attribute changes the actual texts color, but the position marker stays the same color.

Validate a field only if it is populated


c#,wpf,idataerrorinfo
I am having a problem with validating phone numbers. In our system we have two phone numbers which you can store. The problem I am having is that these are optional fields. So I want it to validate the phone number IF and only IF the user has tried to...

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


c#,wpf
I have some sort of cascaded containers that contain notes, where there is one master container, that contains all notes. The notes containers are made in a tree like hierarchy that get more specific the deeper you are in tree-structure. The reason why I have only one list has to...