Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

WPF datagrid filter doesn't work dosen't work

$
0
0

Greetings,

I'm trying to have a WPF data grid results filtered and I can't get it to work.  The filter event never fires and all the rows remain.

   <DockPanel.Resources>
                                  
                                           
     <CollectionViewSource x:Key="DetailsCollection"
                           Filter="PriceDetailsFilter"
                           Source="{Binding Path=PriceChangeDetails,
                           UpdateSourceTrigger=PropertyChanged}" >
     </CollectionViewSource>
                                          
    </DockPanel.Resources>
                                     
                                           
  <wpf:DataGrid  CanUserSortColumns="True" CanUserAddRows="False" IsReadOnly="False"
      Block.TextAlignment="Left"
      ItemsSource="{Binding Source={StaticResource DetailsCollection},
   UpdateSourceTrigger=PropertyChanged}"> 

    public void PriceDetailsFilter(object sender, FilterEventArgs e)        {            e.Accepted = false; // breakpoint never hits                    }

  Does anyone see what I'm doing wrong?

Thanks,

                                                                                                      

Confusing Question About MVVM and Window Closing Event (Setting Cancel to True Works Once)

$
0
0

Strictly adhering to MVVM, I'd like to cancel the closing of a window when the user clicks the "X" or standard Windows close button.

The ViewModel is as follows:

private RelayCommand<CancelEventArgs> _windowClose = null;
public RelayCommand<CancelEventArgs> WindowClose {
	get {
		if (_windowClose == null) {
			_windowClose = new RelayCommand<CancelEventArgs>(
				(args) => {
					args.Cancel = true;
					BeforeExitViewModel tmp = new BeforeExitViewModel();
					WindowManager.ShowWindow(tmp);
				}, (args) => { return (true); });
		}
		return (_windowClose);
	}
}

I pop-up a quick and dirty ViewModel so the user can save changes if they are dirty or cancel the closing event (keep their work open). From the view:

<i:Interaction.Triggers><i:EventTrigger EventName="Closing"><nvis:EventToCommand Command="{Binding WindowClose}" /></i:EventTrigger></i:Interaction.Triggers>

I'm new-ish to MVVM so this really seems correct and simple to me. Trouble is, it works... ONCE!  If the user clicks "Close" then cancels, the window view remains open until they click a second time. Although the RelayCommand DOES fire, it seems setting e.Cancel to true has NO EFFECT.  Why is this?

I know there are workarounds and I can use code behind, but I wanted to post on here to learn from this issue.  Thank you in advance for any helpful replies I get!

About WPF DataGrid in .net4 (decompiling)

$
0
0

I'm currently working on a company complex code base that use the WPF datagrid. The code is totally coupled to the .net 4 wpf datagrid. 

I need to implement a transpose feature on this datagrid and after much work i finally did it.but TADA!!! the biggest bug in the world that simply cant be fixed since WPF datagrid is totally unoverridable... everything is private and internal instead of protected .. i need to change column and cells clipping on scroll from width clipping to height clipping when grid is transposed..

This column/cells clipping is done in private methods and its impossible for me to access or override so to fix the bug..

So my question is would it be legal to just extract parts of the wpf datagrid code and use it?? or at least just set private and internal stuff to virtual protected or public...so that i can extend?? 

I can't understand what the coders thoughts when coding this datagrid like that... its crazy FRAMEWORK SHOULD BE OVERRIDABLE !!!!

How to change new row placeholder template in DataGrid when CanUserAddRows=true?

$
0
0

I'm using a WPF DataGrid bound to an ObservableCollection<T> where each row (aka instance of T) contains a browse and a delete button that are bound as commands to methods of T.

The problem is that I'm using CanUserAddRows=true for data-entry and there is no way to disable the delete button for the new row (since that instance of T isn't instantiated yet).  I.e. I can't control the visibility of a row delete button from the ViewModel because the DataGrid creates a placeholder row when CanUserAddRows is set to TRUE instead of an instance of the object represented in the row that links into the ViewModel.

The core issue is that if the user clicks the delete button on the new row before it has been instantiated, bad things happen.  So I would like to make the delete button invisible or disabled on the new row, at least until it is instantiated.

I think the solution is to override the the template placeholder row uses (instead of using the default template assigned in the DataGrid).  Is it possible to define an alternate template for the placeholder row that removes the delete button?

Thanks in advance.


WPF menu mouse over issue

$
0
0

HI,

I have menu which automatically takes default border when I do Mouse over. I don't want that gray border on mouse over. How would I do that?

Here is code:

<Grid>    

      <Menu Background="Wheat" Margin="0" Width="110" x:Name="TextMenu1" BorderThickness="0">
            <StackPanel Orientation="Horizontal" Margin="0" HorizontalAlignment="Stretch"  Width="110">
                <Image Source="../../Resources/Images/placeholder_textObject.png"  Stretch="Uniform" Width="36"         Height="36" VerticalAlignment="Center"/>
                <TextBlock Text="Text"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"></TextBlock>
            </StackPanel>
        </Menu>

</Grid>

Thanks

Dee

ConvertBack Problem Binding RadioButtons to an Enum

$
0
0

I'm trying to bind radio buttons to an Enum in WPF 4.0.  I don't wish to use the RadioButtons-in-ListBox approach, because, for example, I would like it to work with a nullable Enum with an initial radio button labeled "None" (which isn't one of my Enum constants).

The Convert function is working fine.  I can set the property, and the correct radio button is checked and the others unchecked.

My Enum-to-bool value converter's ConvertBack is initially getting called for each radio button, with one call receiving true and the others false.  The call that receives true is returning the Enum value, and the bound property is properly set and that radio button is checked.  However, for the calls that receive false, I tried returning null and UnsetValue, with the same results, namely, there is a red bounding box around each of my unchecked radio buttons.  As soon as I change the bound Enum, either programmatically or by clicking on an unchecked radio button, the red boxes disappear and everything works great from there, possibly because ConvertBack is never again called with false.

Thank you in advance.

Pulling in a WPF Window from Another WPF Project

$
0
0

Synopsys: I have a WPF class project that defines a <Window> in the xaml. I need to make few if any changes here, and it must stay a class project.

I want to start the class library above as a stand-alone program. The idea is to simply create a WPF Windows Application, and pull in the <Window> defined in the class library above.

I’m showing the code below. The compile error I’m getting from the Windows Application when I try to pull in the Class Library is as follows:

The tag 'UserInterface' does not exist in XML namespace 'clr-namespace:TYBRIN.GFP.FPN.MSGH.UserInterface;assembly=TYBRIN.GFP.FPN.MSGH.UserInterface'. Line 13 Position 10.

This surprised me since intellisense recognizes that the class StatusUI exists in the namespace TYBRIN.GFP.FPN.MSGH.UserInterface.StatusUI.

Here’s the first few lines of WPF from the class library:

<Window x:Class="TYBRIN.GFP.FPN.MSGH.UserInterface.StatusUI"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   xmlns:msgh="clr-namespace:TYBRIN.GFP.FPN.MSGH;assembly=TYBRIN.GFP.FPN.MSGH"

       xmlns:UserInterface="clr-namespace:TYBRIN.GFP.FPN.MSGH.UserInterface"

       xmlns:commands="clr-namespace:TYBRIN.GFP.FPN.MSGH.UserInterface.Commands"

       xmlns:msghConverters="clr-namespace:TYBRIN.GFP.FPN.MSGH.UserInterface.Converters" x:Name="statusUI"

Here’s the xaml code from the Windows Application, where I think I’m pulling in the WPF <Window> from the class library:

<Window x:Class="MessageHandler.MainWindow"

       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

       xmlns:ui="clr-namespace:TYBRIN.GFP.FPN.MSGH.UserInterface;assembly=TYBRIN.GFP.FPN.MSGH.UserInterface"

       Title="MainWindow" Height="400" Width="800">

   <Grid>

       <Grid.RowDefinitions>

           <RowDefinition Height="400" />

       </Grid.RowDefinitions>

       <Grid.ColumnDefinitions>

           <ColumnDefinition Width="800" />

       </Grid.ColumnDefinitions>

       <ui:StatusUI Height="400" Width="800" HorizontalAlignment="Left" Margin="0,0,0,0"></ui:StatusUI>

   </Grid>

</Window>


Randy

Storyboard.Completed firing incorrectly?

$
0
0

I'm using visual states to control a block of text, and I'm having difficulty trapping when the storyboard is completed.

What I want to do is change the text contents when (and only when) the text is down and out of view.

Following the trace of my application, the Storyboard.Completed and VisualStateManager.CurrentStateChanged events are both firing twice at the *beginning* of the animation!

Here is the relevant XAML code:

<VisualStateGroup x:Name="StatusText"><VisualStateGroup.Transitions><VisualTransition GeneratedDuration="0:0:0.4"/></VisualStateGroup.Transitions><VisualState x:Name="StatusUp"><Storyboard Completed="StatusText_UpCompleted"><DoubleAnimationUsingKeyFrames 
			Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" 
			Storyboard.TargetName="statusText"><EasingDoubleKeyFrame KeyTime="0" Value="12"/><EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames 
			Storyboard.TargetProperty="(UIElement.Opacity)" 
			Storyboard.TargetName="statusText"><EasingDoubleKeyFrame KeyTime="0" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="1"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames 
			Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" 
			Storyboard.TargetName="progArc"><EasingDoubleKeyFrame KeyTime="0" Value="12"/><EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames 
			Storyboard.TargetProperty="(UIElement.Opacity)" 
			Storyboard.TargetName="progArc"><EasingDoubleKeyFrame KeyTime="0" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="1"/></DoubleAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="StatusDown"><Storyboard Duration="0:0:0.4" Completed="StatusText_DownCompleted"><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="statusText"><SplineDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/><SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="12"/><EasingDoubleKeyFrame KeyTime="0:0:1" Value="12"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="statusText"><SplineDoubleKeyFrame KeyTime="0" Value="1"/><SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="progArc"><SplineDoubleKeyFrame KeyTime="0:0:0.2" Value="0"/><SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="12"/><EasingDoubleKeyFrame KeyTime="0:0:1" Value="12"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="progArc"><SplineDoubleKeyFrame KeyTime="0" Value="1"/><SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="0"/><EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/></DoubleAnimationUsingKeyFrames></Storyboard>			</VisualState></VisualStateGroup>
The completed method in my code prints "up" or "down" to the console when each event is fired (I got rid of the VisualStateManager.CurrentStateChanged event handler).

To invoke these states, I use this code:

void StatusText_UpCompleted(object sender, EventArgs e) 
{
	System.Console.WriteLine("up");
	if (messages.Count < 1) 
		return;
	if (statusText.Text == messages.Peek()) 
		messages.Dequeue();
	if (messages.Count > 0) 
		VisualStateManager.GoToElementState(layoutRoot, "StatusDown", true);
}

void StatusText_DownCompleted(object sender, EventArgs e) 
{
	System.Console.WriteLine("down");
	statusText.Text = messages.Peek();
	VisualStateManager.GoToElementState(layoutRoot, "StatusUp", true);
}

void Message(string message) 
{
	messages.Enqueue(message);
	if (StatusText.CurrentState != null && StatusText.CurrentState.Name == "StatusUp") 
	{
		VisualStateManager.GoToElementState(layoutRoot, "StatusDown", true);
	}
	else 
	{
		VisualStateManager.GoToElementState(layoutRoot, "StatusUp", true);
	}
}

The text block is supposed to keep moving up and down until there's no more messages left in the queue. This works correctly, except the statusText.Text is being changed before StatusDown is complete. What's going on?

 


"Unable to cast transparent proxy to type" error when calling a third-party dll from powerpoint add-in

$
0
0

I'm calling some code from a third-party dll (an interface to an add-in from a partner company that we work with) from my own powerpoint add-in.

They have provided a sample solution where the following code works as expected.

  Microsoft.Office.Core.COMAddIn thirdPartyAddin= app.COMAddIns.Item("thirdPartyAddin");
  IthirdPartyService x =thirdPartyServiceFactory.GetThirdPartyService(thirdPartyAddin.Object);

I am trying to use the same code and call it inside my plug-in.

What is happening is that I bind to a thirdPartyAdd-in just fine. However, when I call the second line, to get the the interface to the thirdparty service, I get the following exception:

"Unable to cast transparent proxy to type IthirdPartyService" .

What could possibly be the issue? I think I've searched through every single google-generated topic on this issue, an nothing helped.

Thank you in advance

IntraViewModel Communication

$
0
0

I'm fairly new to MVVM and can follow it, but have problems tackling problems that stray from the books and tutorials I've read.Is there a source that covers more involved apps?

Where I'm stuck is intra-ViewModel communication. Let's say you've got an app with an ApplicationVM which drives a "center workspace" ViewModel that switches between content based on what needs to be accomplished. The "center workspace" will have one or more UserControls. (see pics) How should they talk to each other?

Thank You!!!

Outline of ViewModels:

Visual Layout:

WPF Listbox with grouping doesn't update group subtotals on addition of new items

$
0
0

Hi, I have a Listbox that is based on the sorting/grouping example as demonstrated on this page. Everything works fine including adding (except the very first item) and removing items through IEditableCollectionView, which is backed onto an Observable Collection.

The one core problem I am having is the subtotals in the group headers don't update without calling Refresh on the ListBox Items (which is painfully slow with the number of items displayed), or firing a OnCollectionChanged event from the Observable Collection, however any items added show up fine in the list without the refresh.

The subtotals are calculated using a converter.

Have done a bit of research on the issue, but no luck in resolving so far. Has anyone else ran into the same issue? To confirm, adding items is working fine without rebuilding the list, just the grouping subtotals don't update...


If you shake a kettle, does it boil faster?

Manipulate DockPanel or some "Panel"

$
0
0

Hi everyone

I've been developing an application (in XAML with C#) with a left menu, like Outlook Office 2007.

I declared a TabControl with its TabItem (there are 3 TabItems) in the XAML code.

I want to link each TabItem with a DockPanel or something like aPanel in the right side of the display. But i don't know how to do it.

This is the code in XAML where i declare the TabControl and its TabItem:

<TabControl x:Name="TabControl" Template="{StaticResource OutlookTab}"><TabItem x:Name="TabItemUno" Header="TabItemUno"></TabItem><TabItem x:Name="TabItemDos" Header="TabItemDos"></TabItem><TabItem x:Name="TabItemTres" Header="TabItemTres"></TabItem></TabControl>

This is the code where i declare the DockPanels:

<DockPanel Grid.Column="1" x:Name="PanelTabItemUno" HorizontalAlignment="Center" VerticalAlignment="Center"><Label>Todo lo relacionado al TabItemUno</Label></DockPanel><DockPanel Grid.Column="1" x:Name="PanelTabItemDos" HorizontalAlignment="Center" VerticalAlignment="Center"><Label>Todo lo relacionado al TabItemDos</Label></DockPanel><DockPanel Grid.Column="1" x:Name="PanelTabItemTres" HorizontalAlignment="Center" VerticalAlignment="Center"><Label>Todo lo relacionado al TabItemTres</Label></DockPanel>

And, here i try to link the selected TabItem with its DockPanel (if i choose the TabItemOne, in the right side appears the DockPanel PanelTabItemUno):

if (TabItemUno.IsSelected)
{
PanelTabItemUno.IsEnabled = true;
}

But, it does not work ... :(

Any idea?

Thanks to all!


Opening issue with CustomWindow in wpf.

$
0
0

Hi All,

          I am developing an application in WPF ,  in that I made some custom windows. The issue is with opening custom windows ,when we open any custom window it opens at top left most panel of main app but I want  to open that custom window in mid of  app. Please do needful and let me suggest me how I will fix this issue.

Thanks & Regards

swati

How to access child control of template in code behind ?

$
0
0

Hi All,

            I am using button template in resource dictionary and this template  key  access  in button i want to child control access in code behind (.cs) such as:

            Template in  Resource Dictionary :

             <ControlTemplate x:Key="btnTemplate" TargetType="Button">
                   <Grid>
                            <TextBlock x:Name="tb" Height="25" Width="150" ></TextBlock>
                   </Grid>
              </ControlTemplate>

 

             .xaml  

             <Button x:Name="btn" Template="{DynamicResource  btnTemplate}" Height="25" Width="150" >

                    I want to   textblock (x:Name="tb") name access in code behind.

    Thanks

            


aniruddha

WPF app with resize property will crash in Windows 8 OS (0x88980406 )

$
0
0

Dear All

Can you help to analysis this issue?

WPF app with resize property will crash in Windows 8 OS (0x88980406 )

<<Reproduce Step >>

  1. Create a Dialog based WPF application with VS2010.
  2. Mainwindow.xaml <Window> section ResizeMode property with the value of “CanResizeWithGrip or CanResize or CanMinimize”. Set as “NoResize” value will be OK.
  3. Mouse move focus to some control, such as check box/list box etc.
  4. Press Win+D to minimize the dialog UI.
  5. Press Win+D again to restore the dialog UI to desktop. Then the abnormal will be occurred.

<<Coding>>

<Window x:Class="WPF_ResizeMode_Abnormal.MainWindow" ResizeMode="CanResizeWithGrip" ></Window>

<<Notes>>

  1. This issue cannot be reproduced on Windows7 OS.
  2. This issue cannot be reproduced, if ResizeMode property with value NoResize.
  3. This issue can be reproduced with or without ZDP and latest patch files.
  4. This issue can be reproduced on most of TOSHBIA PCs, NOT all the PCs. If one PC can be reproduced once, it can be reproduced every time.
  5. There are many discussion for the HRESULT error code 0x88980406 without solution.
    1. http://connect.microsoft.com/VisualStudio/feedback/details/500410/wpf-crashes-with-error-hresult-0x88980406
    2. http://connect.microsoft.com/VisualStudio/feedback/details/674249/wpf-renderer-thread-exited-with-codes-0x88980406-0x88980403


Guo



How to create menu bar style ?

$
0
0

Hi all,

                  How to create single style for menu bar and sub menu bar items.

       Thanks


aniruddha

WPF 4 touch, AutomationPeer, Windows 7 Tablet Input Services memory leak?

$
0
0

Hi,

I am creating a WPF 4 touch application and was doing memory profiling for my app with ANTS memory profiler and found that the AutomationPeer feature is holding on and not releasing my objects.

Searching around i found this link: http://www.wintellect.com/cs/blogs/sloscialo/archive/2011/04/13/silverlight-memory-leaks-and-automationpeers.aspx

It happens that if the Table Input Service was enabled, the AutomationPeer kicks in automatically. So my question is how can i disable this AutomationPeer but still keeping the Tablet Input Service enabled as I using Windows 7 to run my touch application?

How to images use in menu bar items ?

$
0
0

Hi all,

         I want to use images in menu bar  items by using converter class for get image source. according to upload image.

         Thanks

    


aniruddha


JSON parsing

$
0
0

Hi, This is json result which got from api, can anybody tell me how i deserialize it and bind to Listbox

{
    "api": "getplayerlist",
    "status": "success",
    "message": "Player Details",
    "playerList": [{
        "playerFirstname": "hiren",
        "playerLastname": "raval",
        "playerGender": "male",
        "playerGameplaycount": "1",
        "playerGamewinncount": "0",
        "playerTournamentplaycount": "0",
        "playerTournamentwincount": "0",
        "playerProfileimage": "http:\/\/demo3.idhasofthealth.com\/playgameprize\/web\/images\/noimage.jpg"
    }, {
        "playerFirstname": "shrikant",
        "playerLastname": "shukla",
        "playerGender": "male",
        "playerGameplaycount": "0",
        "playerGamewinncount": "0",
        "playerTournamentplaycount": "0",
        "playerTournamentwincount": "0",
        "playerProfileimage": "http:\/\/demo3.idhasofthealth.com\/playgameprize\/web\/images\/noimage.jpg"
    }, {
        "playerFirstname": "vikram",
        "playerLastname": "pawar",
        "playerGender": "male",
        "playerGameplaycount": "1",
        "playerGamewinncount": "0",
        "playerTournamentplaycount": "0",
        "playerTournamentwincount": "0",
        "playerProfileimage": "http:\/\/demo3.idhasofthealth.com\/playgameprize\/web\/images\/noimage.jpg"
    }]
}

Shivendra Bokade

How to findout is there any data change in my Page?

$
0
0

Hi all,

         I need to find-out is there any change in my page when Clicking Exit Button?

Here i have solution, but its not 100% perfect, so that i am expecting some other solutions.

so i have used INotifyPropertyChanged Interface then just set that boolean Property = true;

Below my Code:-

My MainWindow.Xaml:-

<Window x:Class="DataContextTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="502" Width="892" Name="SampleWinduw" Initialized="SampleWinduw_Initialized"  ><Grid><Label Content="Name:" Height="28" Margin="193,45,604,0" Name="label1" VerticalAlignment="Top" /><Label Content="Address:" Height="28" Margin="193,82,599,0" Name="label2" VerticalAlignment="Top" /><Label Content="Gender:" Height="28" Margin="193,120,597,0" Name="label3" VerticalAlignment="Top" /><TextBox Text="{Binding Path=Name,Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="341,46,0,0" Name="textBox1" VerticalAlignment="Top" Width="225" /><TextBox Text="{Binding Path=Address,Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="341,83,0,0" Name="textBox2" VerticalAlignment="Top" Width="225" /><ComboBox Text="{Binding Path=Gender,Mode=TwoWay}" Height="23" Margin="341,120,0,0" Name="comboBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="144" ><ComboBoxItem Content="Male"/><ComboBoxItem Content="Fenale"/></ComboBox><Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="341,177,0,0" Name="SaveButton" VerticalAlignment="Top" Width="93" /><Button Content="Refresh" Height="23" HorizontalAlignment="Left" Margin="455,177,0,0" Name="RefreshButton" VerticalAlignment="Top" Width="75" Click="RefreshButton_Click" /><Button Content="Exit" Height="23" HorizontalAlignment="Left" Margin="552,177,0,0" Name="ExitButton" VerticalAlignment="Top" Width="104" Click="ExitButton_Click" /></Grid></Window>

My MainWindow.Xaml.CS

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void SampleWinduw_Initialized(object sender, EventArgs e) { this.DataContext = new Person(); } private void RefreshButton_Click(object sender, RoutedEventArgs e) { this.DataContext = new Person(); } private void ExitButton_Click(object sender, RoutedEventArgs e) { Person personEntity = this.DataContext as Person; if (personEntity.IsModified) { if (MessageBox.Show("Close the page and abondan changes","Confirm?",MessageBoxButton.YesNo,MessageBoxImage.Question) == MessageBoxResult.Yes) { this.Close(); } } else { this.Close(); } } }

public class Person : INotifyPropertyChanged
    {
        public bool IsModified { get; set; }

        private string _name = string.Empty;
        private string _address = string.Empty;
        private string _gender = "Male";

        public string Name
        {
            get { return _name; }
            set 
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
        public string Address
        {
            get { return _address; }
            set 
            {
                _address = value;
                RaisePropertyChanged("Address");
            }
        }
        public string Gender
        {
            get { return _gender; }
            set 
            {
                _gender = value;
                RaisePropertyChanged("Gender");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                IsModified = true;
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
 

I hope most of the people will tell the above code is working fine. yes, i too will tell thats working fine.

Please do my Scenario:-

1. Just run the Project.

2. Change Gender value Male to Female. actually here i changed wrongly. so that i will change once again to male.

3. Click Exit Button. this time it will tell that "Close the page and abondon changes?". originally i didn't change any value here.

    i hope i am telling correct.

so any legends have any ideas kindly share with me. In this type of case i don't like to say this type of message to user.

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>