How can I create a breakpoint triggered when when WPF is retrieving the value of my custom DependencyProperty?
I wrote this question poorly the first time. Unfortunately, understanding why my breakpoint is not hit doesn't solve my real problem. This is the question I should have asked. Searching high and low I still can't see how to do this.
If WPF is going to bypass my getter function, is there some other way?
I need this for debugging purposes, to examine the state of my control live in the debugger at the exact moment WPF retrieves this property.
To refresh, below is my custom dependency property
private static readonly DependencyPropertyKey ColorizerPropertyKey =
DependencyProperty.RegisterReadOnly(
nameof(Colorizer),
typeof(SurfaceSeries3DColorizer),
typeof(SurfaceDisplay),
new FrameworkPropertyMetadata());
private static readonly DependencyProperty ColorizerProperty =
ColorizerPropertyKey.DependencyProperty;
public SurfaceSeries3DColorizer Colorizer
{
get => (SurfaceSeries3DColorizer) GetValue(ColorizerProperty);
private set => SetValue(ColorizerPropertyKey, value);
}
...and this is the XAML that binds to it
<tk:SurfaceSeries3D ItemsSource="{Binding Points}"
XValueBinding="X"
YValueBinding="Y"
ZValueBinding="Z"
Colorizer="{Binding Colorizer}"
/>
There is a way for that, but you have to keep in mind that your debuggee (the application you debug) and the debugger itself will become very unresponsive.
So if you're trying to diagnose some nasty and rare occurring bug, this might help. Otherwise, it is pretty useless, because your app will be almost unusable.
Go to the Breakpoints window in Visual Studio and choose New --> Function Breakpoint....
Type in:
System.Windows.DependencyObject.GetValue
Enable the Condition checkbox and enter your condition:
dp == YourNamespace.YourClass.YourDependencyProperty
Here, dp is the GetValue method's argument name (don't change) and YourNamespace.YourClass.YourDependencyProperty is the full name of your dependency property public field (change).
Now, hit F5 and enjoy.
Behind the scenes, the debugger will check each and every call to the System.Windows.DependencyObject.GetValue method, and when the provided argument will be your property, the debugger will break your app.
Note that WPF calls that method very frequently - that's why your app and the debugger will become unresponsive: a condition will be checked on each call, and that condition requires data transfer between debugger and debuggee.
Related
This question already has answers here:
Is there a notification mechanism for when a dependency property has changed?
(4 answers)
Closed 3 years ago.
Our Silverlight app contains a third-party control, which contains some ScrollBars (among other things). In order to troubleshoot a problem, I want to be able to stop in the debugger whenever the third-party control modifies the Minimum or Maximum properties of any of its scrollbars. Then I'll be able to look at the stack trace and learn more about what's going on.
If I was interested in the ScrollBars' Value property, that would all be easy -- ScrollBar has a ValueChanged event, so I could just add some throwaway code that hooks that event on the ScrollBar, set a breakpoint inside my event handler, and debug away. But there are no corresponding CLR events for MinimumChanged or MaximumChanged, so it won't be that simple.
I ran across a blog post that talks about using DependencyPropertyDescriptor to get dependency property change events, but unfortunately, DependencyPropertyDescriptor doesn't exist in Silverlight.
How can I get to the point where I can set a breakpoint that fires whenever the ScrollBar's Minimum and Maximum properties change?
The following idea springs to my mind:
Create a user control with a dependency property. (The XAML within the user control won't actually be used, we just need the dependency property.)
Bind the user control's dependency property to the Minimum or Maximum property of the third party control (assuming they are also dependency properties).
In the code-behind of the user control, add a PropertyChangedCallback to the dependency property and drop a breakpoint in that.
This approach should allow you to set a breakpoint that fires whenever the Minimum or Maximum property changes. However, I can't guarantee that you'll get a stacktrace that will help you.
The code-behind of the user control could look something like this:
public partial class DPContainer : UserControl
{
public static readonly DependencyProperty DebugValueProperty =
DependencyProperty.Register("DebugValue", typeof(object), typeof(DPContainer), new PropertyMetadata(DebugValue_Changed));
public DPContainer()
{
InitializeComponent();
}
public object DebugValue
{
get { return GetValue(DebugValueProperty); }
set { SetValue(DebugValueProperty, value); }
}
private static void DebugValue_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
// Drop a breakpoint in this method.
}
Assuming that you have a ScrollBar with x:Name="someScrollBar", you could then add something like the following to your XAML:
<local:DPContainer DebugValue="{Binding Path=Minimum, ElementName=someScrollBar}" />
I am relatively new to MVVM, and I am trying to code up a basic Status Bar for an MVVM WPF application. I think I have the gist of things, but for some reason, the status bar does not always update, and I am not sure why.
In my ViewModel, I have a basic property that I update when I change a status message:
public string StatusMessage
{
get { return _statusMessage; }
set
{
if (value == _statusMessage) return;
_statusMessage = value;
base.OnPropertyChanged(() => this.StatusMessage);
}
}
My OnPropertyChanged method (which I have in a base ViewModel class that implements INotifyPropertyChanged) looks like so (got this idea from Gunther Foidl; wish I could claim credit for it because I think it's slick but I'm not quite that smart):
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> exp)
{
MemberExpression me = exp.Body as MemberExpression;
string propName = me.Member.Name;
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
At any rate, this all works great for all of my controls except one. On my MainWindow.xaml file, I have a StatusBarItem control bound to the above property, like so (the rest of the XAML has been trimmed for space reasons):
<StatusBarItem Grid.Column="0">
<TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Path=StatusMessage}" />
</StatusBarItem>
When I run my application (which hits a couple of DBs in addition to generating a document from template and a bunch of other fairly resource-intensive stuff), some, but not all, messages show up on the status bar. I have debugged and verified that the messages all make it into the StatusMessage property, above (and the ensuing private variable), they just don't seem to be refreshing in the UI.
I have looked at several examples that use BackgroundWorker instances for ProgressBar controls, but haven't seen any for StatusBarItem controls, and am not really sure how to translate one to the other.
I have also used Tasks before in previous C# 4.0 and WPF apps, and figure it's probably a good way to go, but I haven't really been able to figure out how/where to designate the UI task (I've always done it in the code-behind for the MainWindow before, but I'm striving for a zero-code-behind to stay in keeping with MVVM here).
I'm pretty sure that a multi-threaded approach is the way to go; I just don't know enough about one approach (I know a little bit of this and a little bit of that) to make it work. I did see a couple of posts that used the older threading approach directly, but I pretty much stayed away from multithreading programming until I started using Tasks with .NET 4.0 (finding them a little easier to comprehend and keep track of), so I had a bit of trouble making sense of them.
Can anyone take pity on me and point me in the right direction, or suggest further debugging I can do? Thanks!
1)Reflection based binding can be source of error sometimes because of inlining. Try to see what happens if you notifypropertychanged with simple string instead of reflection.
2) if you are using multi threads there maybe a chance that you setup StatusMessage not from UIThread in that case it won't be able to update UI, you could invoke setter code on UI Dispatcher to see if that helps
3) check whether binding works , in constructor of xaml form modify StatusMessage directly on VM and see whether the change is shown on UI without invoking multithreaded service calls which introduce additional variables to simple textblock - string binding
4) if that doesn't help you could create a simple xaml form with single textblock bind it to your big viewmodel and see what happens, if nothing works you can begin cutting VM class to make it simpler so binding eventually starts to work and you find an error
5) if you think that statusbar is the problem see if single textblock without statusbar (extract xaml part from your example) works
Somewhere the notification does not get through.
I would try :
Add a dummy valueconverter on the textbinding so you can set a breakpoint and see if you are called
Dispatching the property set to set the value at a "better" time - that is sometimes nessesary.
Dispatching the set might do the trick.
I've started to make myself a list of "WPF gotchas": things that bug me and that I had to write down to remember because I fall for them every time....
Now, I'm pretty sure you all stumbled upon similar situations at one point, and I would like you to share your experience on the subject:
What is the gotcha that gets you all the time? the one you find the most annoying?
(I have a few issues that seem to be without explanation, maybe your submissions will explain them)
Here are a few of my "personnal" gotchas (randomly presented):
For a MouseEvent to be fired even when the click is on the "transparent" background of a control (e.g. a label) and not just on the content (the Text in this case), the control's Background has to be set to "Brushes.Transparent" and not just "null" (default value for a label)
A WPF DataGridCell's DataContext is the RowView to whom the cell belong, not the CellView
When inside a ScrollViewer, a Scrollbar is managed by the scrollviewer itself (i.e. setting properties such as ScrollBar.Value is without effect)
Key.F10 is not fired when you press "F10", instead you get Key.System and you have to go look for e.SystemKey to get the Key.F10
... and now you're on.
Always watch the output window for
binding errors. Ignoring the output
window is a recipe for tears.
Use PresentationTraceOptions.TraceLevel="High" in a binding to get verbose binding information when debugging binding failures.
Make static, unchanging resources such as brushes PresentationOptions:Freeze="True" to save resources at runtime.
Use the WPF DataGrid as a datagrid. Modifying it to behave like Excel is a massive pain in the butt.
BindingList<T> does not play well with CollectionViewSource. Expose ObservableCollection<T> from your viewmodels instead.
The internet supplies half a dozen different ideas for displaying CueBanner text in a WPF textbox. They are all broken.
1) One that used to get me every half an hour when I was making my transition from WinForms: use TextBlock instead of Label when putting random text on the UI (or don't use any tag at all, if the text is static)!
2) DataTriggers/Triggers can't be put into Control.Triggers, but have to go into Control.Styles/Style/Style.Triggers
3) Property's type must implement IList, not IList<T>, if the property is to be recognized by XAML as a collection property.
4) Bindings capture exceptions.
5) Use singleton converters/static converter class, so you don't have to create a new converter every time you use it.
6) A type for default value of DependencyProperty has to be clearly specified: 0u as uint, (float) 0 as float, 0.0 as double...
7) It matters if the control's property definitions are before or after its content.
8) NEVER use PropertyMetadata to set a default value of reference type DependencyProperty. The same object reference will be assigned to all instances of the owning class.
When first starting out, the main gotchas that would get me would be
Lists not updating due to forgetting
to use ObservableCollection
Properties not being updated either
forgetting to add OnPropertyChanged
or incorrectly typing the property
name
Recently I have stumbled across these issues
Application failing to start due to
corrupt font cache
StringFormat localization issues
If enabled, Button.IsCancel assigns false to Window.DialogResult but Button.IsDefault no.
They are so similar and for me it seemed intuitive at first that both should close dialog. I usually break MVVM and fix this in code-behind
Button.IsCancel + Command = Dialog won't close (Window.DialogResult left unassigned) but Command executes
As I understand it: If IsCancel had higher priority than Command then on Esc it would assign 'false' to DialogResult and Command won't be called. Or, if Command would have higher priority then it would be called first and DialogResult would be assigned. I don't understand how it is skipped?
Binding swallows exceptions!
It not only steals time while debugging it is also wrong from the OOP point of view because if exception is thrown it means that something exceptional had happened somewhere in our system (anything from wrong data supply to unauthorized access to memory failure) so it can be handled only if you know what to do. You can't just catch(Exception){} catch 'em all and then ignore. If there is unknown exception in program it should notify user, log and close not pretend like everything is ok...
HeaderContent can have only one child control and has no padding
Everything should have padding even logical controls (containers), right? I think it is inconsistent. What do you think?
If you set focus to ListBox via FocusManager.FocusedElement you still won't be able to switch it's content with keyboard because focus is set to ListBoxes frame not it's content. I think I don't know other UI API that would expose something like controls frame to UI programmer it should be encapsulated from us because abstractly ListBox represents a list, it is just a list of things not a list of things in a box. ok it has box in its name but still... We almost have two different controls here.
MVVM not breaking fix
ListBox.IsSynchronizedWithCurrentItem by default is false so if you assign different value or null to ItesSource then SelectedItem still holds old value until user selects something from a new list. It could mess up CanExecute for example. Need to set it every time by hand.
No binding exposed in PasswordBox results in time waste and dirty hacks... But still it has a string property PasswordBox.Password exposed so don't even try to argue about security because Snoop...
It is not a gotcha but table layout is so IE6 IMO. Container design helps separate content from its layout.
Because every time I need to change something in places I need to mess up with Grid.Row and Grid.Column. Yes, we have DockPanel, StackPanel and others but you can't do some column alignment inside of them. (And DockPanel is like completely separate gotcha) If UniformGrid would be more customizable it would be ideal I think. You always need to choose between Grid and Panels and usually if you gain something you loose something else.
I got a pretty nifty one last week:
When Templating a RichTextBox, the event handling inside the template follows a strange route that has nothing to do neither with tunnelling nor bubbling
e.g.: In the case of an event that is supposed to tunnel: the event first tunnels through the ContentPresenter, then it tunnels back from the top of the template.
see my question on the subject
ToolTips and ContextMenus not sharing the DataContext of its owner? I think that gets everyone at first
There is no clean way to handle validation in WPF, I am not a fan of magic string which IDataErrorInfo offers by default:
public string this[string columnName]
{
if (columnName == "FirstName")
{
if (string.IsNullOrEmpty(FirstName))
result = "Please enter a First Name";
}
}
However, I have tried many frameworks like SimpleMVVM, FluentValidation and MVVMValidation and BY FAR MVVM Validation is the best getting to do stuff like:
Validator.AddRule(() => RangeStart,
() => RangeEnd,
() => RuleResult.Assert(RangeEnd > RangeStart, "RangeEnd must be grater than RangeStart");
My personal favorite is this one:
public double MyVariable
{
get { return (double)GetValue(MyVariableProperty); }
set { SetValue(MyVariableProperty, value); }
}
public static readonly DependencyProperty MyVariableProperty = DependencyProperty.Register(
"MyVariable", typeof(double), typeof(MyControl), new UIPropertyMetadata(0));
Try it, once this property is declared it will crash. Why? Because 0 can't be assigned to a double using reflection apparently.
Not really a gotcha but an advice: Use Snoop or something similar, if you don't use it you must be crazy ... Crazy i tell ya!
Binding.StringFormat only works if the type of the target property is string.
TreeView's SelectedItem property is not settable. Instead you have to bind TreeViewItem's IsSelected property to your item's viewmodel and set your selection there.
ListBox's SelectedItem, on the other hand is settable, but item selection is not equal to item focus. If you want to implement proper keyboard navigation along with selecting items from within viewmodel, you have to implement manual focus fix, like:
public void FixListboxFocus()
{
if (lbFiles.SelectedItem != null)
{
lbFiles.ScrollIntoView(lbFiles.SelectedItem);
lbFiles.UpdateLayout();
var item = lbFiles.ItemContainerGenerator.ContainerFromItem(viewModel.SelectedFile);
if (item != null && item is ListBoxItem listBoxItem && !listBoxItem.IsFocused)
listBoxItem.Focus();
}
}
...and call it every time you change selected item from viewmodel:
SelectedFile = files.FirstOrDefault();
viewAccess.FixListboxFocus();
I'm having one hell of a time trying to get my databinding to work correctly. I have reason to believe that what I'm trying to accomplish can't be done, but we'll see what answers I get.
I've got a UserControl. This UserControl contains nothing more than a button. Now within the code behind, I've got a property name IsBookmarked. When IsBookmarked is set, code is run that animates the look of the button. The idea is that you click the button and it visually changes. We'll call this UserControl a Bookmark control.
Now I have another control, which we'll call the FormControl. My FormControl contains a child Bookmark control. I've tried to do databinding on my Bookmark control, but it's not working. Here's some code to help you out.
This is the XAML and Loaded event handler of my control. As you can see it contains a child element that is a custom control (bookmark). So once this control loads, it's DataContext is set to an new instance of an Employee object. Silverlight also sets the DataContext property of my child bookmark control to the same instance. I've verified this by debugging. If my parent has a valid DataContext set then why can't my child control (bookmark) property databind to it?
<UserControl ......>
<q:Bookmark x:Name="BookMarkControl1" IsBookmarked="{Binding IsSiteBookmarked}" />
</UserControl>
public void Control_Loaded(object sender, EventArgs e)
{
DataContext = new Employee { IsSiteBookmarked = True };
}
This is my custom control below. Obviously it contains more than this, but for readability I've trimmed it down to the property I'm trying to databind to.
//this is the bookmark control. I've included this control within another control, and I'm trying to databind to properties within my parents DataContext
public partial class Bookmark : UserControl
{
bool _IsBookmarked= false;
public bool IsBookmarked
{
get {return _IsBookmarked;}
set {
_IsBookmarked= value;
SwitchMode(value);
}
}
}
UPDATE
Got some javascript errors that I should mention. Firebug reports a AG_E_PARSER_BAD_PROPERTY_VALUE exception. It doesn't seem like my databinding is even working yet.
Make your IsBookmarked property on the Bookmark control a dependency property.
I presume Control_Loaded is a part of your FormControl, in which case I'm not sure you are using DataContext properly. Best double check that.
UPDATE: Yes, you are using the DataContext properly. AG_E_PARSER_BAD_PROPERTY_VALUE indicates you need to make the IsBookmarked property a dependency property, like so:
Public Property IsBookmarked() As Boolean
Get
Return Me.GetValue(IsBookmarkedProperty)
End Get
Set(ByVal value As Boolean)
Me.SetValue(IsBookmarkedProperty, value)
End Set
End Property
Public Shared ReadOnly IsBookmarkedProperty As DependencyProperty = DependencyProperty.Register("IsBookmarked", GetType(Boolean), GetType(Bookmark), New PropertyMetadata(New PropertyChangedCallback(AddressOf OnIsBookmarkedPropertyChanged)))
Private Shared Sub OnIsBookmarkedPropertyChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim cntrl As Bookmark = TryCast(d, Bookmark)
cntrl.SetIsBookmarked(e.NewValue)
End Sub
If you only need to store the value for later use, then you don't need to do anything in the OnIsBookmarkedPropertyChanged procedure, But I put some code there as an example anyway.
Good Luck!
I don't recall the exact order in which databinding is evaluated (and I'm too lazy to go look it up), but as I recall, it initially happens BEFORE the form's Loaded event fires, and without making the IsBookmarked property a dependency property, or at least using INotifyPropertyChanged, it may have trouble establishing the datacontext appropriately. I'd recommend either implementing INotifyPropertyChanged or making IsBookmarked a dependency property. DataBinding is tough enough to get right in the best of circumstances (see my long, bad-tempered rant about it here), and you'll just be making it more difficult on yourself if you aren't setting up your properties in the way that it expects.
The control exposes a IsSiteBookmarked property(which I believe should be a DependencyProperty) but the control is binding to a IsBookmarked which is not shown. Is this intentional? Have you checked your Visual Studio output window for binding errors?
Addition 1:
Since you have fixed the typo in your question and added that there is an error being reported.
Start by clearing up the AG_E_PARSER_BAD_PROPERTY_VALUE problem. Is there a line number and start position in the error message? Start looking there. One strategy is to start taking out XAML until there is no longer an error. This will narrow down the offending code.
Running in debug, mode check for binding errors in the output window.
You might want to also post the Employee class code, especially the IsSiteBookmarked property.
Typically when doing databinding to an object you will want to leverage the INotifyPropertyChanged interface and implement that so that the control can properly invalidate it's property value. Unless you use INotifyPropertyChanged with Mode=TwoWay then any code that changes your DataContext's IsSiteBookmarked will have no effect.
I have rebuilt Josh Smith's CommandSink example from scratch and my version runs without error except that my command buttons are grayed out. I assume this is because there is something somewhere not set correctly so that the commands never get set to CanExecute = true or at some point get set to CanExecute = false.
But since the databinding is essentially going on in the XAML, I am not sure where to "set a breakpoint on the command" so I can see at what time a button is assigned CanExecute = false or e.g. is NOT assigned CanExecute = true.
Essentially I have these command bindings in a view:
<UserControl.CommandBindings>
<sink:CommandSinkBinding Command="vm:CustomerViewModel.CloseCommand"/>
<sink:CommandSinkBinding Command="vm:CustomerViewModel.ShowInformationCommand"/>
</UserControl.CommandBindings>
and in my CustomerViewModel the command is defined like this:
public static readonly RoutedCommand CloseCommand = new RoutedCommand();
public bool CanBeClosed
{
get { return _customer.IsOpen; }
}
public void Close()
{
_customer.IsOpen = false;
this.OnPropertyChanged("CanBeClosed");
this.OnPropertyChanged("CanBeApproved");
}
But since my understanding of MVVM right now is that you set up your M-VM-M, run your application and things "get data bound and just work".
I guess I am looking for something like a "Page Cycle" as in ASP.NET in which to step through to find out when my commands are CanExecute = true and when they are CanExecute = false.
How could one go about debugging an WPF/MVVM pattern like this where the databinding is not done explicitly in the code, and hence one cannot step-through debug in the classic sense?
Answer:
Although this article that Gishu mentioned was helpful in general regarding how to go about debugging databinding issues, and generally answered my question on how to do just that, it didn't help me in my particular case.
For what it's worth, I figured my particular issue with this code out by doing a line-per-line comparison with Josh Smith's original code and found these two lines that were missing from the CommandSinkBinding.OnCommandSinkChanged method:
if (!ConfigureDelayedProcessing(depObj, commandSink))
ProcessCommandSinkChanged(depObj, commandSink);
First point:
To debug XAML Binding you can add reference to Diagnostics from WindowsBase dll to the XAML file,
then when binding to some property add PresentationTraceSources.TraceLevel. When you run it check out the output window.
XAML sample :
<TextBlock Text="{Binding someProperty, diagnostics:PresentationTraceSources.TraceLevel=High}"/>
Second point:
your command being grayed out means that your binding works! What doesn't happen is that the command doesn't refresh it's state, meaning CanExe() method ran and set the command to "can't exe state", however it never does check again if it can toggle its state back to "can exe". There are many ways to do it, but basically when a certain property changes in your ViewModel, refresh your command state:
in Prism, for example you can call someCommand.RaiseCanExecuteChanged ();