Search Results

Search found 108 results on 5 pages for 'dependencyobject'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Using Linq methods causes missing references to DependencyObject in WindowsBase

    - by Jason Coyne
    I have some c# source that I want to compile using CodeDom within my application (for a plugin) Everything works fine, except if I use a Linq extension function on some of my collections var dict = new Dictionary<KeyType, ValueType>(); .... dict.Any(KV=>KV.Key == "Some Key); When I try to compile source that has this code, it CodeDom complains that I am missing a reference to DependencyObject in WindowsBase. I do not understand why this is happening. Neither the Dictionary class, or the Any extension method reference that class, which apparently is part of Windows.Forms I would normally just ignore the quirk, make the CodeDom add a reference and move on, but Apparently WindowsBase is special and is not always distributed and I don't want to cause issues for users that may not have it installed correctly.

    Read the article

  • NullReferenceException when changing skin/theme via Application.Current.Resources

    - by CoolCat
    I am writing an wpf application with multiple skins. The code to switch theme is as below: try { Application.Current.Resources.MergedDictionaries.Add( resource ); } catch( Exception ex ) { } The first time the code is called (to switch to a new theme), it is executed successfully; however, any subsequent calls to the same code would throw System.NullReferenceException. The way I set up my themes are similar to what described here: http://www.codewrecks.com/blog/index.php/2008/05/22/simple-skinnable-and-theme-management-in-wpf-user-interface/. Has anyone seen this error before? How do I go about debugging this since the exception is thrown else where? Any help is greatly appreciated. StackTrace: at System.Windows.EffectiveValueEntry.GetFlattenedEntry(RequestFlags requests) at System.Windows.DependencyObject.EvaluateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry newEntry, OperationType operationType) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp) at System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents) at System.Windows.StyleHelper.DoStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle) at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache) at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp) at System.Windows.FrameworkElement.UpdateStyleProperty() at System.Windows.TreeWalkHelper.InvalidateStyleAndReferences(DependencyObject d, ResourcesChangeInfo info, Boolean containsTypeOfKey) at System.Windows.TreeWalkHelper.OnResourcesChanged(DependencyObject d, ResourcesChangeInfo info, Boolean raiseResourceChangedEvent) at System.Windows.TreeWalkHelper.OnResourcesChangedCallback(DependencyObject d, ResourcesChangeInfo info) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnResourcesChange(FrameworkElement fe, FrameworkContentElement fce, ResourcesChangeInfo info) at System.Windows.Application.InvalidateResourceReferenceOnWindowCollection(WindowCollection wc, ResourcesChangeInfo info) at System.Windows.ResourceDictionary.NotifyOwners(ResourcesChangeInfo info) at System.Windows.ResourceDictionary.OnMergedDictionariesChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Windows.ResourceDictionaryCollection.InsertItem(Int32 index, ResourceDictionary item) at System.Collections.ObjectModel.Collection`1.Add(T item)

    Read the article

  • WPF UserControl Style results in error message

    - by Didier
    Hi I'm new in WPF so I try to create a WPF UserControl. My problem is about the style of the user control I've Created. On a design time I got this error message Can only base on a Style with target type that is base type 'RichTextBox'. at System.Windows.Style.Seal() at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache) at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp) at System.Windows.FrameworkElement.UpdateStyleProperty() at System.Windows.TreeWalkHelper.InvalidateStyleAndReferences(DependencyObject d, ResourcesChangeInfo info, Boolean containsTypeOfKey) at System.Windows.TreeWalkHelper.OnResourcesChanged(DependencyObject d, ResourcesChangeInfo info, Boolean raiseResourceChangedEvent) at System.Windows.TreeWalkHelper.OnResourcesChangedCallback(DependencyObject d, ResourcesChangeInfo info) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker1._VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.VisitNode(FrameworkElement fe) at System.Windows.DescendentsWalker1.VisitNode(DependencyObject d) at System.Windows.DescendentsWalker1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnResourcesChange(FrameworkElement fe, FrameworkContentElement fce, ResourcesChangeInfo info) at System.Windows.ResourceDictionary.NotifyOwners(ResourcesChangeInfo info) at System.Windows.ResourceDictionary.EndInit() at MS.Internal.Host.Designer.OnAppResourcesChanged(Object sender, EventArgs e) at MS.Internal.Host.Designer.get_View() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() And at a run time An error Message type XamlParseException Occurs and the message is: Cannot create instance of 'RichTextBox' defined in assembly 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Can only base on a Style with target type that is base type 'RichTextBox'. Error at object 'System.Windows.Controls.Grid' in markup file 'NameSpace;component/usercontrols /myusercontrol.xaml' Line 125 Position 14. My user control have 3 richtextboxes 1 textbox and 3 dropdownlist and about 10 buttons. I think The problem is about to define the style of my user control, can anyone help me to do this. Thanks

    Read the article

  • Call bindings for DependencyObject when DependencyProperites are changed

    - by melculetz
    Is there a way to notify a DependencyObject's bindinigs when the inner DependencyProperties have changed? For example, I have this class: public class BackgroundDef : DependencyObject { public static readonly DependencyProperty Color1Property = DependencyProperty.Register("Color1", typeof(Color), typeof(Background), new UIPropertyMetadata(Colors.White)); public static readonly DependencyProperty UseBothColorsProperty = DependencyProperty.Register("UseBothColors", typeof(bool), typeof(Background), new UIPropertyMetadata(false)); public static readonly DependencyProperty Color2Property = DependencyProperty.Register("Color2", typeof(Color), typeof(Background), new UIPropertyMetadata(Colors.White)); public Color Color1 { set { SetValue(Color1Property, value); } get { return (Color)GetValue(Color1Property); } } public bool UseBothColors { set { SetValue(UseBothColorsProperty, value); } get { return (bool)GetValue(UseBothColorsProperty); } } public Color Color2 { set { SetValue(Color2Property, value); } get { return (Color)GetValue(Color2Property); } } } For which I have 3 separate two-way bindings that set the values for Color1, Color2 and UseBothColors. But I also have a binding for a BackgroundDef instance, which should create a Brush and draw the background of a button (either a single color, or two gradient colors). My problem is that the two-way bindings for the DependencyProperties update the properties, but the binding for the class instance is not called, as apparently the entire object does not change. Any idea how I could call the bindings for the DependencyObject when the DependencyProperties are changed?

    Read the article

  • Adorning a non-DependencyObject with a DependencyProperty

    - by Rob
    I'm trying to bind to a WinForms control's DataSource property in my WPF application but I'm not having much luck... Falafel.com gives it a shot, but although it claimes that a DependencyObject is not required to perform the binding, that seems to be the only way of doing it. Has anyone done this before?

    Read the article

  • Binding to a collection of DependencyObjects in Silverlight 4

    - by Meik
    As of Silverlight 4 it is possible to data bind against a DependencyObject (instead of a Framework element in previous versions). So far so good, but how do I bind agains a collection of DependencyObjects. The DataContext is not passed from the ObservableCollection to the collection elements, so that the DependencyProperties of the DependencyObjects are never called (neither the changed events). Neither the DependencyObject offers SetBinding or DataContext to initialize the binding manually. Thanks for any advice here.

    Read the article

  • WPF custom DependencyProperty notify changes

    - by morsanu
    Hey guys I have a class called MyComponent and it has a DependencyProperty caled BackgroundProperty. public class MyComponent { public MyBackground Background { get { return (MyBackground)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(MyBackground), typeof(MyComponent), new FrameworkPropertyMetadata(default(MyBackground), new PropertyChangedCallback(OnPropertyChanged))); } MyBackground is a class that derives from DependencyObject and it has some DependencyProperties. public class MyBackground : DependencyObject { public Color BaseColor { set { SetValue(BaseColorProperty, value); } get { return (Color)GetValue(BaseColorProperty); } } public static readonly DependencyProperty BaseColorProperty = DependencyProperty.Register("BaseColor", typeof(Color), typeof(MyBackground ), new UIPropertyMetadata(Colors.White)); [...] } Now, what I want is when a property from MyBackground is changed, MyComponent to be notified that MyBackground has changed and the PropertyChangedCallback named OnPropertyChanged to be called.

    Read the article

  • Is it getting to be time for C# to support compile-time macros?

    - by Robert Rossney
    Thus far, Microsoft's C# team has resisted adding formal compile-time macro capabilities to the language. There are aspects of programming with WPF that seem (to me, at least) to be creating some compelling use cases for macros. Dependency properties, for instance. It would be so nice to just be able to do something like this: [DependencyProperty] public string Foo { get; set; } and have the body of the Foo property and the static FooProperty property be generated automatically at compile time. Or, for another example an attribute like this: [NotifyPropertyChanged] public string Foo { get; set; } that would make the currently-nonexistent preprocessor produce this: private string _Foo; public string Foo { get { return _Foo; } set { _Foo = value; OnPropertyChanged("Foo"); } } You can implement change notification with PostSharp, and really, maybe PostSharp is a better answer to the question. I really don't know. Assuming that you've thought about this more than I have, which if you've thought about it at all you probably have, what do you think? (This is clearly a community wiki question and I've marked it accordingly.)

    Read the article

  • WPF- Why can't my custom textbox be selected?

    - by highone
    I have this custom textbox that I am working on and I can use it in xaml, but when I run my app I cannot select it or type in it. Here is my code: public class ModdedTextBox : TextBox { private bool selectionStartChangeFromUI; private bool selectionLengthChangeFromUI; private bool selectedTextChangeFromUI; static ModdedTextBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ModdedTextBox), new FrameworkPropertyMetadata(typeof(ModdedTextBox))); //this.SelectionChanged += this.OnSelectionChanged; //PropertyDescriptor VerticalOffsetProperty = TypeDescriptor.GetProperties(typeof(ModdedTextBox))["VerticalOffset"]; //VerticalOffsetProperty.AddValueChanged(this, this.OnVerticalOffsetChanged); } public static readonly DependencyProperty BindableSelectionStartProperty = DependencyProperty.Register( "BindableSelectionStart", typeof(int), typeof(ModdedTextBox), new PropertyMetadata(OnBindableSelectionStartChanged)); public static readonly DependencyProperty BindableSelectionLengthProperty = DependencyProperty.Register( "BindableSelectionLength", typeof(int), typeof(ModdedTextBox), new PropertyMetadata(OnBindableSelectionLengthChanged)); public static readonly DependencyProperty BindableSelectedTextProperty = DependencyProperty.Register( "BindableSelectedText", typeof(string), typeof(ModdedTextBox), new PropertyMetadata(OnBindableSelectedTextChanged)); public static readonly DependencyProperty DelayedTextProperty = DependencyProperty.Register( "DelayedText", typeof(string), typeof(ModdedTextBox), new PropertyMetadata(OnDelayedTextChanged)); public int BindableSelectionStart { get { return (int)this.GetValue(BindableSelectionStartProperty); } set { this.SetValue(BindableSelectionStartProperty, value); } } public int BindableSelectionLength { get { return (int)this.GetValue(BindableSelectionLengthProperty); } set { this.SetValue(BindableSelectionLengthProperty, value); } } public string BindableSelectedText { get { return (string)this.GetValue(BindableSelectedTextProperty); } private set { this.SetValue(BindableSelectedTextProperty, value); } } public string DelayedText { get { return (string)this.GetValue(DelayedTextProperty); } private set { this.SetValue(DelayedTextProperty, value); } } private static void OnBindableSelectionStartChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { var textBox = dependencyObject as ModdedTextBox; if (!textBox.selectionStartChangeFromUI) { int newValue = (int)args.NewValue; textBox.SelectionStart = newValue; } else { textBox.selectionStartChangeFromUI = false; } } private static void OnBindableSelectionLengthChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { var textBox = dependencyObject as ModdedTextBox; if (!textBox.selectionLengthChangeFromUI) { int newValue = (int)args.NewValue; textBox.SelectionLength = newValue; } else { textBox.selectionLengthChangeFromUI = false; } } private static void OnBindableSelectedTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { var textBox = dependencyObject as ModdedTextBox; if (!textBox.selectedTextChangeFromUI) { string newValue = (string)args.NewValue; textBox.BindableSelectedText = newValue; } else { textBox.selectedTextChangeFromUI = false; } } private static void OnDelayedTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { } private void OnSelectionChanged(object sender, RoutedEventArgs e) { if (this.BindableSelectionStart != this.SelectionStart) { this.selectionStartChangeFromUI = true; this.BindableSelectionStart = this.SelectionStart; } if (this.BindableSelectionLength != this.SelectionLength) { this.selectionLengthChangeFromUI = true; this.BindableSelectionLength = this.SelectionLength; } if (this.BindableSelectedText != this.SelectedText) { this.selectedTextChangeFromUI = true; this.BindableSelectedText = this.SelectedText; } } private void OnVerticalOffsetChanged(object sender, EventArgs e) { MessageBox.Show("hello the vertical offset works"); } }

    Read the article

  • Visual Tree Enumeration

    - by codingbloke
    I feel compelled to post this blog because I find I’m repeatedly posting this same code in silverlight and windows-phone-7 answers in Stackoverflow. One common task that we feel we need to do is burrow into the visual tree in a Silverlight or Windows Phone 7 application (actually more recently I found myself doing this in WPF as well).  This allows access to details that aren’t exposed directly by some controls.  A good example of this sort of requirement is found in the “Restoring exact scroll position of a listbox in Windows Phone 7”  question on stackoverflow.  This required that the scroll position of the scroll viewer internal to a listbox be accessed. A caveat One caveat here is that we should seriously challenge the need for this burrowing since it may indicate that there is a design problem.  Burrowing into the visual tree or indeed burrowing out to containing ancestors could represent significant coupling between module boundaries and that generally isn’t a good idea. Why isn’t this idea just not cast aside as a no-no?  Well the whole concept of a “Templated Control”, which are in extensive use in these applications, opens the coupling between the content of the visual tree and the internal code of a control.   For example, I can completely change the appearance and positioning of elements that make up a ComboBox.  The ComboBox control relies on specific template parts having set names of a specified type being present in my template.  Rightly or wrongly this does kind of give license to writing code that has similar coupling. Hasn’t this been done already? Yes it has.  There are number of blogs already out there with similar solutions.  In fact if you are using Silverlight toolkit the VisualTreeExtensions class already provides this feature.  However I prefer my specific code because of the simplicity principle I hold to.  Only write the minimum code necessary to give all the features needed.  In this case I add just two extension methods Ancestors and Descendents, note I don’t bother with “Get” or “Visual” prefixes.  Also I haven’t added Parent or Children methods nor additional “AndSelf” methods because all but Children is achievable with the addition of some other Linq methods.  I decided to give Descendents an additional overload for depth hence a depth of 1 is equivalent to Children but this overload is a little more flexible than simply Children. So here is the code:- VisualTreeEnumeration public static class VisualTreeEnumeration {     public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)     {         int count = VisualTreeHelper.GetChildrenCount(root);         for (int i = 0; i < count; i++)         {             var child = VisualTreeHelper.GetChild(root, i);             yield return child;             if (depth > 0)             {                 foreach (var descendent in Descendents(child, --depth))                     yield return descendent;             }         }     }     public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)     {         return Descendents(root, Int32.MaxValue);     }     public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)     {         DependencyObject current = VisualTreeHelper.GetParent(root);         while (current != null)         {             yield return current;             current = VisualTreeHelper.GetParent(current);         }     } }   Usage examples The following are some examples of how to combine the above extension methods with Linq to generate the other axis scenarios that tree traversal code might require. Missing Axis Scenarios var parent = control.Ancestors().Take(1).FirstOrDefault(); var children = control.Descendents(1); var previousSiblings = control.Ancestors().Take(1)     .SelectMany(p => p.Descendents(1).TakeWhile(c => c != control)); var followingSiblings = control.Ancestors().Take(1)     .SelectMany(p => p.Descendents(1).SkipWhile(c => c != control).Skip(1)); var ancestorsAndSelf = Enumerable.Repeat((DependencyObject)control, 1)     .Concat(control.Ancestors()); var descendentsAndSelf = Enumerable.Repeat((DependencyObject)control, 1)     .Concat(control.Descendents()); You might ask why I don’t just include these in the VisualTreeEnumerator.  I don’t on the principle of only including code that is actually needed.  If you find that one or more of the above  is needed in your code then go ahead and create additional methods.  One of the downsides to Extension methods is that they can make finding the method you actually want in intellisense harder. Here are some real world usage scenarios for these methods:- Real World Scenarios //Gets the internal scrollviewer of a ListBox ScrollViewer sv = someListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault(); // Get all text boxes in current UserControl:- var textBoxes = this.Descendents().OfType<TextBox>(); // All UIElement direct children of the layout root grid:- var topLevelElements = LayoutRoot.Descendents(0).OfType<UIElement>(); // Find the containing `ListBoxItem` for a UIElement:- var container = elem.Ancestors().OfType<ListBoxItem>().FirstOrDefault(); // Seek a button with the name "PinkElephants" even if outside of the current Namescope:- var pinkElephantsButton = this.Descendents()     .OfType<Button>()     .FirstOrDefault(b => b.Name == "PinkElephants"); //Clear all checkboxes with the name "Selector" in a Treeview foreach (CheckBox checkBox in elem.Descendents()     .OfType<CheckBox>().Where(c => c.Name == "Selector")) {     checkBox.IsChecked = false; }   The last couple of examples above demonstrate a common requirement of finding controls that have a specific name.  FindName will often not find these controls because they exist in a different namescope. Hope you find this useful, if not I’m just glad to be able to link to this blog in future stackoverflow answers.

    Read the article

  • CheckBox Command Behaviors for Silverlight MVVM Pattern

    - by Blake Blackwell
    I am trying to detect when an item is checked, and which item is checked in a ListBox using Silverlight 4 and the Prism framework. I found this example on creating behaviors, and tried to follow it but nothing is happening in the debugger. I have three questions: Why isn't my command executing? How do I determine which item was checked (i.e. pass a command parameter)? How do I debug this? (i.e. where can I put break points to begin stepping into this) Here is my code: View: <ListBox x:Name="MyListBox" ItemsSource="{Binding PanelItems, Mode=TwoWay}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding Enabled}" my:Checked.Command="{Binding Check}" /> <TextBlock x:Name="DisplayName" Text="{Binding DisplayName}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ViewModel: public MainPageViewModel() { _panelItems.Add( new PanelItem { Enabled = true, DisplayName = "Test1" } ); Check = new DelegateCommand<object>( itemChecked ); } public void itemChecked( object o ) { //do some stuff } public DelegateCommand<object> Check { get; set; } Behavior Class public class CheckedBehavior : CommandBehaviorBase<CheckBox> { public CheckedBehavior( CheckBox element ) : base( element ) { element.Checked +=new RoutedEventHandler(element_Checked); } void element_Checked( object sender, RoutedEventArgs e ) { base.ExecuteCommand(); } } Command Class public static class Checked { public static ICommand GetCommand( DependencyObject obj ) { return (ICommand) obj.GetValue( CommandProperty ); } public static void SetCommand( DependencyObject obj, ICommand value ) { obj.SetValue( CommandProperty, value ); } public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached( "Command", typeof( CheckBox ), typeof( Checked ), new PropertyMetadata( OnSetCommandCallback ) ); public static readonly DependencyProperty CheckedCommandBehaviorProperty = DependencyProperty.RegisterAttached( "CheckedCommandBehavior", typeof( CheckedBehavior ), typeof( Checked ), null ); private static void OnSetCommandCallback( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e ) { CheckBox element = dependencyObject as CheckBox; if( element != null ) { CheckedBehavior behavior = GetOrCreateBehavior( element ); behavior.Command = e.NewValue as ICommand; } } private static CheckedBehavior GetOrCreateBehavior( CheckBox element ) { CheckedBehavior behavior = element.GetValue( CheckedCommandBehaviorProperty ) as CheckedBehavior; if( behavior == null ) { behavior = new CheckedBehavior( element ); element.SetValue( CheckedCommandBehaviorProperty, behavior ); } return behavior; } public static CheckedBehavior GetCheckCommandBehavior( DependencyObject obj ) { return (CheckedBehavior) obj.GetValue( CheckedCommandBehaviorProperty ); } public static void SetCheckCommandBehavior( DependencyObject obj, CheckedBehavior value ) { obj.SetValue( CheckedCommandBehaviorProperty, value ); } } I used this article to get me started, but I'll readily admit this is over my head.

    Read the article

  • Multibinding File-Paths into a Button ControlTemplate

    - by Bill
    I am trying to develop an application that uses a number of images that are stored in a seperate remote file location. The file-paths to the UI elements are stored within the Application Settings. Although I understand how to access the images from Applications Settings using a MultiBinding and a value converter, I'm not sure how to integrate the Multibinding into the ImageButton ControlTemplate below. Can anyone steer me in the right direction? <Image.Source> <MultiBinding Converter="{StaticResource MyConverter}"> <Binding Source="{StaticResource Properties.Settings}" Path="Default.pathToInterfaceImages" /> <Binding Source="ScreenSaver.png"></Binding> </MultiBinding> </Image.Source> <Button Click="btn_ScreenSaver_Click" Style="{DynamicResource ThreeImageButton}" local:ThreeImageButton.Image="C:\Skins\ScreenSaver_UP.png" local:ThreeImageButton.MouseOverImage="C:\Skins\ScreenSaver_OVER.png" local:ThreeImageButton.PressedImage="C:\Skins\ScreenSaver_DOWN.png"/> <Style x:Key="ThreeImageButton" TargetType="{x:Type Button}"> <Setter Property="FontSize" Value="10"/> <Setter Property="Height" Value="34"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <StackPanel Orientation="Horizontal" > <Image Name="PART_Image" Source= "{Binding Path=(local:ThreeImageButton.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" /> </StackPanel> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.MouseOverImage), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.PressedImage), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Source" Value="{Binding Path=(local:ThreeImageButton.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" TargetName="PART_Image"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> public class ThreeImageButton : DependencyObject { // Add three new Dependency Properties to the Button Class to hold the // path to each of the images that are bound to the control, displayed // during normal, mouse-over and pressed states. public static readonly DependencyProperty ImageProperty; public static readonly DependencyProperty MouseOverImageProperty; public static readonly DependencyProperty PressedImageProperty; public static ImageSource GetImage(DependencyObject obj) { return (ImageSource)obj.GetValue(ImageProperty); } public static ImageSource GetMouseOverImage(DependencyObject obj) { return (ImageSource)obj.GetValue(MouseOverImageProperty); } public static ImageSource GetPressedImage(DependencyObject obj) { return (ImageSource)obj.GetValue(PressedImageProperty); } public static void SetImage(DependencyObject obj, ImageSource value) { obj.SetValue(ImageProperty, value); } public static void SetMouseOverImage(DependencyObject obj, ImageSource value) { obj.SetValue(MouseOverImageProperty, value); } public static void SetPressedImage(DependencyObject obj, ImageSource value) { obj.SetValue(PressedImageProperty, value); } // Register each property with the control. static ThreeImageButton() { var metadata = new FrameworkPropertyMetadata((ImageSource)null); ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ThreeImageButton), metadata); var metadata1 = new FrameworkPropertyMetadata((ImageSource)null); MouseOverImageProperty = DependencyProperty.RegisterAttached("MouseOverImage", typeof(ImageSource), typeof(ThreeImageButton), metadata1); var metadata2 = new FrameworkPropertyMetadata((ImageSource)null); PressedImageProperty = DependencyProperty.RegisterAttached("PressedImage", typeof(ImageSource), typeof(ThreeImageButton), metadata2); } }

    Read the article

  • ListBoxItem.Parent returns nothing, unable to get it thru VisualTreeHelper.GetParent either

    - by Shimmy
    How do I extract the parent container of a ListBoxItem? In the following example I can go till the ListBoxItem, higher than that I get Nothing: <ListBox Name="lbAddress"> <ListBox.ItemTemplate> <DataTemplate> <Button Click="Button_Click"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Private Sub Button_Click(sender As Button, e As RoutedEventArgs) Dim lbAddress = GetAncestor(Of ListBox) 'Result: Nothing End Sub Public Shared Function GetAncestor(Of T)(reference As DependencyObject) As T Dim parent = GetParent(reference) While parent IsNot Nothing AndAlso Not parent.GetType.Equals(GetType(T)) parent = GetAncestor(Of T)(parent) End While If parent IsNot Nothing Then _ Return If(parent.GetType Is GetType(T), parent, Nothing) Return Nothing End Sub Public Function GetParent(reference As DependencyObject) As DependencyObject Dim parent As DependencyObject = Nothing If TypeOf reference Is FrameworkElement Then parent = DirectCast(reference, FrameworkElement).Parent ElseIf TypeOf reference Is FrameworkContentElement Then parent = DirectCast(reference, FrameworkContentElement).Parent End If Return If(parent, VisualTreeHelper.GetParent(reference)) End Function Update This is what happens (note that the 'parent' variable remains null):

    Read the article

  • Find ListBox from its child?

    - by Shimmy
    How do I extract the parent container of a ListBoxItem? In the following example I can go till the ListBoxItem, higher than that I get Nothing: <ListBox Name="lbAddress"> <ListBox.ItemTemplate> <DataTemplate> <Button Click="Button_Click"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Private Sub Button_Click(sender As Button, e As RoutedEventArgs) Dim lbAddress = GetAncestor(Of ListBox) 'Result: Nothing End Sub Public Shared Function GetAncestor(Of T)(reference As DependencyObject) As T Dim parent = GetParent(reference) While parent IsNot Nothing AndAlso Not parent.GetType.Equals(GetType(T)) parent = GetVisualAncestor(Of T)(parent) End While If parent IsNot Nothing Then _ Return If(parent.GetType Is GetType(T), parent, Nothing) Return Nothing End Sub Public Function GetParent(reference As DependencyObject) As DependencyObject Dim parent As DependencyObject = Nothing If TypeOf reference Is FrameworkElement Then parent = DirectCast(reference, FrameworkElement).Parent ElseIf TypeOf reference Is FrameworkContentElement Then parent = DirectCast(reference, FrameworkContentElement).Parent End If Return If(parent, VisualTreeHelper.GetParent(reference)) End Function

    Read the article

  • datagrid height issue in nested datagrid( when using three data grid)

    - by prince23
    hi, i have a nested datagrid(which is of three data grid). here i am able to show data with no issue. the first datagrid has 5 rows the main problem that comes here is when you click any row in first datagrid i show 2 datagrid( which has 10 rows) lets say i click 3 row in 2 data grid. it show further records in third datagrid. again when i click 5 row in 2 data grid it show further records in third datagrid. now all the recods are shown fine when u try to collpase the 3 row in 2 data grid it collpase but the issue is the height what the third datagrid which took space for showing the records( we can see a blank space showing between the main 2 datagrid and third data grid) in every grid first column i have an button where i am writing this code for expand and collpase this is the functionality i am implementing in all the datagrid button where i do expand collpase. hope my question is clear . any help would great private void btn1_Click(object sender, RoutedEventArgs e) { try { Button btnExpandCollapse = sender as Button; Image imgScore = (Image)btnExpandCollapse.FindName("img"); DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is DataGridRow)) { dep = VisualTreeHelper.GetParent(dep); } // if we found the clicked row if (dep != null && dep is DataGridRow) { DataGridRow row = (DataGridRow)dep; // change the details visibility if (row.DetailsVisibility == Visibility.Collapsed) { imgScore.Source = new BitmapImage(new Uri("/Images/a1.JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Visible; } else { imgScore.Source = new BitmapImage(new Uri("/Images/a2JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Collapsed; } } } catch (System.Exception) { } } --------------------------------------- 2 datagrid private void btn2_Click(object sender, RoutedEventArgs e) { try { Button btnExpandCollapse = sender as Button; Image imgScore = (Image)btnExpandCollapse.FindName("img"); DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is DataGridRow)) { dep = VisualTreeHelper.GetParent(dep); } // if we found the clicked row if (dep != null && dep is DataGridRow) { DataGridRow row = (DataGridRow)dep; // change the details visibility if (row.DetailsVisibility == Visibility.Collapsed) { imgScore.Source = new BitmapImage(new Uri("/Images/a1.JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Visible; } else { imgScore.Source = new BitmapImage(new Uri("/Images/a2JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Collapsed; } } } catch (System.Exception) { } } ----------------- 3 datagrid private void btn1_Click(object sender, RoutedEventArgs e) { try { Button btnExpandCollapse = sender as Button; Image imgScore = (Image)btnExpandCollapse.FindName("img"); DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is DataGridRow)) { dep = VisualTreeHelper.GetParent(dep); } // if we found the clicked row if (dep != null && dep is DataGridRow) { DataGridRow row = (DataGridRow)dep; // change the details visibility if (row.DetailsVisibility == Visibility.Collapsed) { imgScore.Source = new BitmapImage(new Uri("/Images/a1.JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Visible; } else { imgScore.Source = new BitmapImage(new Uri("/Images/a2JPG", UriKind.Relative)); row.DetailsVisibility = Visibility.Collapsed; } } } catch (System.Exception) { } }**

    Read the article

  • Silverlight 3.0 Custom ListBox DataTemplate has a checkbox, checked event not firing

    - by Bhaskar
    The datatemplate for the ListBox is set dynamically by XamlReader.Load. I am subscribing to Checked event by getting the CheckBox object using VisualTreeHelper.GetChild. This event is not getting fired Code Snippet public void SetListBox() { lstBox.ItemTemplate = XamlReader.Load(@"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name=""DropDownTemplate""><Grid x:Name='RootElement'><CheckBox x:Name='ChkList' Content='{Binding " + TextContent + "}' IsChecked='{Binding " + BindValue + ", Mode=TwoWay}'/></Grid></DataTemplate>") as DataTemplate; CheckBox chkList = (CheckBox)GetChildObject((DependencyObject)_lstBox.ItemTemplate.LoadContent(), "ChkList"); chkList.Checked += delegate { SetSelectedItemText(); }; } public CheckBox GetChildObject(DependencyObject obj, string name) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject c = VisualTreeHelper.GetChild(obj, i); if (c.GetType().Equals(typeof(CheckBox)) && (String.IsNullOrEmpty(name) || ((FrameworkElement)c).Name == name)) { return (CheckBox)c; } DependencyObject gc = GetChildObject(c, name); if (gc != null) return (CheckBox)gc; } return null; } How to handle the checked event? Please help

    Read the article

  • Pass Data to Data Template Selector

    - by Michael Sync
    How do you guys pass the data (parameter) to DataTemplate Selector? The only one that I can think of is to use an attached property in DataTemplate Selector? Example: public class DisableWeekendsSelection : DataTemplateSelector { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible", Justification = "DependencyProperty")] public static readonly DependencyProperty Parameter = DependencyProperty.RegisterAttached("Parameter", typeof(ObservableCollection<Date>), typeof(DisableWeekendsSelection), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public static ObservableCollection<Date> GetParameter(DependencyObject dp) { return dp.GetValue(Parameter) as ObservableCollection<Date>; } public static void SetParameter(DependencyObject dp, ObservableCollection<Date> value) { dp.SetValue(Parameter, value); } public override DataTemplate SelectTemplate(object item, DependencyObject container) { The problem with this approach is that I'm not able to get the value of Parameter in SelectTemplate method. Any suggestion would be appreciated. Thanks in advance.

    Read the article

  • Silverlight Recruiting Application Part 5 - Jobs Module / View

    Now we starting getting into a more code-heavy portion of this series, thankfully though this means the groundwork is all set for the most part and after adding the modules we will have a complete application that can be provided with full source. The Jobs module will have two concerns- adding and maintaining jobs that can then be broadcast out to the website. How they are displayed on the site will be handled by our admin system (which will just poll from this common database), so we aren't too concerned with that, but rather with getting the information into the system and allowing the backend administration/HR users to keep things up to date. Since there is a fair bit of information that we want to display, we're going to move editing to a separate view so we can get all that information in an easy-to-use spot. With all the files created for this module, the project looks something like this: And now... on to the code. XAML for the Job Posting View All we really need for the Job Posting View is a RadGridView and a few buttons. This will let us both show off records and perform operations on the records without much hassle. That XAML is going to look something like this: 01.<Grid x:Name="LayoutRoot" 02.Background="White"> 03.<Grid.RowDefinitions> 04.<RowDefinition Height="30" /> 05.<RowDefinition /> 06.</Grid.RowDefinitions> 07.<StackPanel Orientation="Horizontal"> 08.<Button x:Name="xAddRecordButton" 09.Content="Add Job" 10.Width="120" 11.cal:Click.Command="{Binding AddRecord}" 12.telerik:StyleManager.Theme="Windows7" /> 13.<Button x:Name="xEditRecordButton" 14.Content="Edit Job" 15.Width="120" 16.cal:Click.Command="{Binding EditRecord}" 17.telerik:StyleManager.Theme="Windows7" /> 18.</StackPanel> 19.<telerikGrid:RadGridView x:Name="xJobsGrid" 20.Grid.Row="1" 21.IsReadOnly="True" 22.AutoGenerateColumns="False" 23.ColumnWidth="*" 24.RowDetailsVisibilityMode="VisibleWhenSelected" 25.ItemsSource="{Binding MyJobs}" 26.SelectedItem="{Binding SelectedJob, Mode=TwoWay}" 27.command:SelectedItemChangedEventClass.Command="{Binding SelectedItemChanged}"> 28.<telerikGrid:RadGridView.Columns> 29.<telerikGrid:GridViewDataColumn Header="Job Title" 30.DataMemberBinding="{Binding JobTitle}" 31.UniqueName="JobTitle" /> 32.<telerikGrid:GridViewDataColumn Header="Location" 33.DataMemberBinding="{Binding Location}" 34.UniqueName="Location" /> 35.<telerikGrid:GridViewDataColumn Header="Resume Required" 36.DataMemberBinding="{Binding NeedsResume}" 37.UniqueName="NeedsResume" /> 38.<telerikGrid:GridViewDataColumn Header="CV Required" 39.DataMemberBinding="{Binding NeedsCV}" 40.UniqueName="NeedsCV" /> 41.<telerikGrid:GridViewDataColumn Header="Overview Required" 42.DataMemberBinding="{Binding NeedsOverview}" 43.UniqueName="NeedsOverview" /> 44.<telerikGrid:GridViewDataColumn Header="Active" 45.DataMemberBinding="{Binding IsActive}" 46.UniqueName="IsActive" /> 47.</telerikGrid:RadGridView.Columns> 48.</telerikGrid:RadGridView> 49.</Grid> I'll explain what's happening here by line numbers: Lines 11 and 16: Using the same type of click commands as we saw in the Menu module, we tie the button clicks to delegate commands in the viewmodel. Line 25: The source for the jobs will be a collection in the viewmodel. Line 26: We also bind the selected item to a public property from the viewmodel for use in code. Line 27: We've turned the event into a command so we can handle it via code in the viewmodel. So those first three probably make sense to you as far as Silverlight/WPF binding magic is concerned, but for line 27... This actually comes from something I read onDamien Schenkelman's blog back in the day for creating an attached behavior from any event. So, any time you see me using command:Whatever.Command, the backing for it is actually something like this: SelectedItemChangedEventBehavior.cs: 01.public class SelectedItemChangedEventBehavior : CommandBehaviorBase<Telerik.Windows.Controls.DataControl> 02.{ 03.public SelectedItemChangedEventBehavior(DataControl element) 04.: base(element) 05.{ 06.element.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(element_SelectionChanged); 07.} 08.void element_SelectionChanged(object sender, SelectionChangeEventArgs e) 09.{ 10.// We'll only ever allow single selection, so will only need item index 0 11.base.CommandParameter = e.AddedItems[0]; 12.base.ExecuteCommand(); 13.} 14.} SelectedItemChangedEventClass.cs: 01.public class SelectedItemChangedEventClass 02.{ 03.#region The Command Stuff 04.public static ICommand GetCommand(DependencyObject obj) 05.{ 06.return (ICommand)obj.GetValue(CommandProperty); 07.} 08.public static void SetCommand(DependencyObject obj, ICommand value) 09.{ 10.obj.SetValue(CommandProperty, value); 11.} 12.public static readonly DependencyProperty CommandProperty = 13.DependencyProperty.RegisterAttached("Command", typeof(ICommand), 14.typeof(SelectedItemChangedEventClass), new PropertyMetadata(OnSetCommandCallback)); 15.public static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 16.{ 17.DataControl element = dependencyObject as DataControl; 18.if (element != null) 19.{ 20.SelectedItemChangedEventBehavior behavior = GetOrCreateBehavior(element); 21.behavior.Command = e.NewValue as ICommand; 22.} 23.} 24.#endregion 25.public static SelectedItemChangedEventBehavior GetOrCreateBehavior(DataControl element) 26.{ 27.SelectedItemChangedEventBehavior behavior = element.GetValue(SelectedItemChangedEventBehaviorProperty) as SelectedItemChangedEventBehavior; 28.if (behavior == null) 29.{ 30.behavior = new SelectedItemChangedEventBehavior(element); 31.element.SetValue(SelectedItemChangedEventBehaviorProperty, behavior); 32.} 33.return behavior; 34.} 35.public static SelectedItemChangedEventBehavior GetSelectedItemChangedEventBehavior(DependencyObject obj) 36.{ 37.return (SelectedItemChangedEventBehavior)obj.GetValue(SelectedItemChangedEventBehaviorProperty); 38.} 39.public static void SetSelectedItemChangedEventBehavior(DependencyObject obj, SelectedItemChangedEventBehavior value) 40.{ 41.obj.SetValue(SelectedItemChangedEventBehaviorProperty, value); 42.} 43.public static readonly DependencyProperty SelectedItemChangedEventBehaviorProperty = 44.DependencyProperty.RegisterAttached("SelectedItemChangedEventBehavior", 45.typeof(SelectedItemChangedEventBehavior), typeof(SelectedItemChangedEventClass), null); 46.} These end up looking very similar from command to command, but in a nutshell you create a command based on any event, determine what the parameter for it will be, then execute. It attaches via XAML and ties to a DelegateCommand in the viewmodel, so you get the full event experience (since some controls get a bit event-rich for added functionality). Simple enough, right? Viewmodel for the Job Posting View The Viewmodel is going to need to handle all events going back and forth, maintaining interactions with the data we are using, and both publishing and subscribing to events. Rather than breaking this into tons of little pieces, I'll give you a nice view of the entire viewmodel and then hit up the important points line-by-line: 001.public class JobPostingViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005.public DelegateCommand<object> AddRecord { get; set; } 006.public DelegateCommand<object> EditRecord { get; set; } 007.public DelegateCommand<object> SelectedItemChanged { get; set; } 008.public RecruitingContext context; 009.private QueryableCollectionView _myJobs; 010.public QueryableCollectionView MyJobs 011.{ 012.get { return _myJobs; } 013.} 014.private QueryableCollectionView _selectionJobActionHistory; 015.public QueryableCollectionView SelectedJobActionHistory 016.{ 017.get { return _selectionJobActionHistory; } 018.} 019.private JobPosting _selectedJob; 020.public JobPosting SelectedJob 021.{ 022.get { return _selectedJob; } 023.set 024.{ 025.if (value != _selectedJob) 026.{ 027._selectedJob = value; 028.NotifyChanged("SelectedJob"); 029.} 030.} 031.} 032.public SubscriptionToken editToken = new SubscriptionToken(); 033.public SubscriptionToken addToken = new SubscriptionToken(); 034.public JobPostingViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 035.{ 036.// set Unity items 037.this.eventAggregator = eventAgg; 038.this.regionManager = regionmanager; 039.// load our context 040.context = new RecruitingContext(); 041.this._myJobs = new QueryableCollectionView(context.JobPostings); 042.context.Load(context.GetJobPostingsQuery()); 043.// set command events 044.this.AddRecord = new DelegateCommand<object>(this.AddNewRecord); 045.this.EditRecord = new DelegateCommand<object>(this.EditExistingRecord); 046.this.SelectedItemChanged = new DelegateCommand<object>(this.SelectedRecordChanged); 047.SetSubscriptions(); 048.} 049.#region DelegateCommands from View 050.public void AddNewRecord(object obj) 051.{ 052.this.eventAggregator.GetEvent<AddJobEvent>().Publish(true); 053.} 054.public void EditExistingRecord(object obj) 055.{ 056.if (_selectedJob == null) 057.{ 058.this.eventAggregator.GetEvent<NotifyUserEvent>().Publish("No job selected."); 059.} 060.else 061.{ 062.this._myJobs.EditItem(this._selectedJob); 063.this.eventAggregator.GetEvent<EditJobEvent>().Publish(this._selectedJob); 064.} 065.} 066.public void SelectedRecordChanged(object obj) 067.{ 068.if (obj.GetType() == typeof(ActionHistory)) 069.{ 070.// event bubbles up so we don't catch items from the ActionHistory grid 071.} 072.else 073.{ 074.JobPosting job = obj as JobPosting; 075.GrabHistory(job.PostingID); 076.} 077.} 078.#endregion 079.#region Subscription Declaration and Events 080.public void SetSubscriptions() 081.{ 082.EditJobCompleteEvent editComplete = eventAggregator.GetEvent<EditJobCompleteEvent>(); 083.if (editToken != null) 084.editComplete.Unsubscribe(editToken); 085.editToken = editComplete.Subscribe(this.EditCompleteEventHandler); 086.AddJobCompleteEvent addComplete = eventAggregator.GetEvent<AddJobCompleteEvent>(); 087.if (addToken != null) 088.addComplete.Unsubscribe(addToken); 089.addToken = addComplete.Subscribe(this.AddCompleteEventHandler); 090.} 091.public void EditCompleteEventHandler(bool complete) 092.{ 093.if (complete) 094.{ 095.JobPosting thisJob = _myJobs.CurrentEditItem as JobPosting; 096.this._myJobs.CommitEdit(); 097.this.context.SubmitChanges((s) => 098.{ 099.ActionHistory myAction = new ActionHistory(); 100.myAction.PostingID = thisJob.PostingID; 101.myAction.Description = String.Format("Job '{0}' has been edited by {1}", thisJob.JobTitle, "default user"); 102.myAction.TimeStamp = DateTime.Now; 103.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 104.} 105., null); 106.} 107.else 108.{ 109.this._myJobs.CancelEdit(); 110.} 111.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 112.} 113.public void AddCompleteEventHandler(JobPosting job) 114.{ 115.if (job == null) 116.{ 117.// do nothing, new job add cancelled 118.} 119.else 120.{ 121.this.context.JobPostings.Add(job); 122.this.context.SubmitChanges((s) => 123.{ 124.ActionHistory myAction = new ActionHistory(); 125.myAction.PostingID = job.PostingID; 126.myAction.Description = String.Format("Job '{0}' has been added by {1}", job.JobTitle, "default user"); 127.myAction.TimeStamp = DateTime.Now; 128.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 129.} 130., null); 131.} 132.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 133.} 134.#endregion 135.public void GrabHistory(int postID) 136.{ 137.context.ActionHistories.Clear(); 138._selectionJobActionHistory = new QueryableCollectionView(context.ActionHistories); 139.context.Load(context.GetHistoryForJobQuery(postID)); 140.} Taking it from the top, we're injecting an Event Aggregator and Region Manager for use down the road and also have the public DelegateCommands (just like in the Menu module). We also grab a reference to our context, which we'll obviously need for data, then set up a few fields with public properties tied to them. We're also setting subscription tokens, which we have not yet seen but I will get into below. The AddNewRecord (50) and EditExistingRecord (54) methods should speak for themselves for functionality, the one thing of note is we're sending events off to the Event Aggregator which some module, somewhere will take care of. Since these aren't entirely relying on one another, the Jobs View doesn't care if anyone is listening, but it will publish AddJobEvent (52), NotifyUserEvent (58) and EditJobEvent (63)regardless. Don't mind the GrabHistory() method so much, that is just grabbing history items (visibly being created in the SubmitChanges callbacks), and adding them to the database. Every action will trigger a history event, so we'll know who modified what and when, just in case. ;) So where are we at? Well, if we click to Add a job, we publish an event, if we edit a job, we publish an event with the selected record (attained through the magic of binding). Where is this all going though? To the Viewmodel, of course! XAML for the AddEditJobView This is pretty straightforward except for one thing, noted below: 001.<Grid x:Name="LayoutRoot" 002.Background="White"> 003.<Grid x:Name="xEditGrid" 004.Margin="10" 005.validationHelper:ValidationScope.Errors="{Binding Errors}"> 006.<Grid.Background> 007.<LinearGradientBrush EndPoint="0.5,1" 008.StartPoint="0.5,0"> 009.<GradientStop Color="#FFC7C7C7" 010.Offset="0" /> 011.<GradientStop Color="#FFF6F3F3" 012.Offset="1" /> 013.</LinearGradientBrush> 014.</Grid.Background> 015.<Grid.RowDefinitions> 016.<RowDefinition Height="40" /> 017.<RowDefinition Height="40" /> 018.<RowDefinition Height="40" /> 019.<RowDefinition Height="100" /> 020.<RowDefinition Height="100" /> 021.<RowDefinition Height="100" /> 022.<RowDefinition Height="40" /> 023.<RowDefinition Height="40" /> 024.<RowDefinition Height="40" /> 025.</Grid.RowDefinitions> 026.<Grid.ColumnDefinitions> 027.<ColumnDefinition Width="150" /> 028.<ColumnDefinition Width="150" /> 029.<ColumnDefinition Width="300" /> 030.<ColumnDefinition Width="100" /> 031.</Grid.ColumnDefinitions> 032.<!-- Title --> 033.<TextBlock Margin="8" 034.Text="{Binding AddEditString}" 035.TextWrapping="Wrap" 036.Grid.Column="1" 037.Grid.ColumnSpan="2" 038.FontSize="16" /> 039.<!-- Data entry area--> 040. 041.<TextBlock Margin="8,0,0,0" 042.Style="{StaticResource LabelTxb}" 043.Grid.Row="1" 044.Text="Job Title" 045.VerticalAlignment="Center" /> 046.<TextBox x:Name="xJobTitleTB" 047.Margin="0,8" 048.Grid.Column="1" 049.Grid.Row="1" 050.Text="{Binding activeJob.JobTitle, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 051.Grid.ColumnSpan="2" /> 052.<TextBlock Margin="8,0,0,0" 053.Grid.Row="2" 054.Text="Location" 055.d:LayoutOverrides="Height" 056.VerticalAlignment="Center" /> 057.<TextBox x:Name="xLocationTB" 058.Margin="0,8" 059.Grid.Column="1" 060.Grid.Row="2" 061.Text="{Binding activeJob.Location, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 062.Grid.ColumnSpan="2" /> 063. 064.<TextBlock Margin="8,11,8,0" 065.Grid.Row="3" 066.Text="Description" 067.TextWrapping="Wrap" 068.VerticalAlignment="Top" /> 069. 070.<TextBox x:Name="xDescriptionTB" 071.Height="84" 072.TextWrapping="Wrap" 073.ScrollViewer.VerticalScrollBarVisibility="Auto" 074.Grid.Column="1" 075.Grid.Row="3" 076.Text="{Binding activeJob.Description, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 077.Grid.ColumnSpan="2" /> 078.<TextBlock Margin="8,11,8,0" 079.Grid.Row="4" 080.Text="Requirements" 081.TextWrapping="Wrap" 082.VerticalAlignment="Top" /> 083. 084.<TextBox x:Name="xRequirementsTB" 085.Height="84" 086.TextWrapping="Wrap" 087.ScrollViewer.VerticalScrollBarVisibility="Auto" 088.Grid.Column="1" 089.Grid.Row="4" 090.Text="{Binding activeJob.Requirements, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 091.Grid.ColumnSpan="2" /> 092.<TextBlock Margin="8,11,8,0" 093.Grid.Row="5" 094.Text="Qualifications" 095.TextWrapping="Wrap" 096.VerticalAlignment="Top" /> 097. 098.<TextBox x:Name="xQualificationsTB" 099.Height="84" 100.TextWrapping="Wrap" 101.ScrollViewer.VerticalScrollBarVisibility="Auto" 102.Grid.Column="1" 103.Grid.Row="5" 104.Text="{Binding activeJob.Qualifications, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 105.Grid.ColumnSpan="2" /> 106.<!-- Requirements Checkboxes--> 107. 108.<CheckBox x:Name="xResumeRequiredCB" Margin="8,8,8,15" 109.Content="Resume Required" 110.Grid.Row="6" 111.Grid.ColumnSpan="2" 112.IsChecked="{Binding activeJob.NeedsResume, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 113. 114.<CheckBox x:Name="xCoverletterRequiredCB" Margin="8,8,8,15" 115.Content="Cover Letter Required" 116.Grid.Column="2" 117.Grid.Row="6" 118.IsChecked="{Binding activeJob.NeedsCV, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 119. 120.<CheckBox x:Name="xOverviewRequiredCB" Margin="8,8,8,15" 121.Content="Overview Required" 122.Grid.Row="7" 123.Grid.ColumnSpan="2" 124.IsChecked="{Binding activeJob.NeedsOverview, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 125. 126.<CheckBox x:Name="xJobActiveCB" Margin="8,8,8,15" 127.Content="Job is Active" 128.Grid.Column="2" 129.Grid.Row="7" 130.IsChecked="{Binding activeJob.IsActive, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 131. 132.<!-- Buttons --> 133. 134.<Button x:Name="xAddEditButton" Margin="8,8,0,10" 135.Content="{Binding AddEditButtonString}" 136.cal:Click.Command="{Binding AddEditCommand}" 137.Grid.Column="2" 138.Grid.Row="8" 139.HorizontalAlignment="Left" 140.Width="125" 141.telerik:StyleManager.Theme="Windows7" /> 142. 143.<Button x:Name="xCancelButton" HorizontalAlignment="Right" 144.Content="Cancel" 145.cal:Click.Command="{Binding CancelCommand}" 146.Margin="0,8,8,10" 147.Width="125" 148.Grid.Column="2" 149.Grid.Row="8" 150.telerik:StyleManager.Theme="Windows7" /> 151.</Grid> 152.</Grid> The 'validationHelper:ValidationScope' line may seem odd. This is a handy little trick for catching current and would-be validation errors when working in this whole setup. This all comes from an approach found on theJoy Of Code blog, although it looks like the story for this will be changing slightly with new advances in SL4/WCF RIA Services, so this section can definitely get an overhaul a little down the road. The code is the fun part of all this, so let us see what's happening under the hood. Viewmodel for the AddEditJobView We are going to see some of the same things happening here, so I'll skip over the repeat info and get right to the good stuff: 001.public class AddEditJobViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005. 006.public RecruitingContext context; 007. 008.private JobPosting _activeJob; 009.public JobPosting activeJob 010.{ 011.get { return _activeJob; } 012.set 013.{ 014.if (_activeJob != value) 015.{ 016._activeJob = value; 017.NotifyChanged("activeJob"); 018.} 019.} 020.} 021. 022.public bool isNewJob; 023. 024.private string _addEditString; 025.public string AddEditString 026.{ 027.get { return _addEditString; } 028.set 029.{ 030.if (_addEditString != value) 031.{ 032._addEditString = value; 033.NotifyChanged("AddEditString"); 034.} 035.} 036.} 037. 038.private string _addEditButtonString; 039.public string AddEditButtonString 040.{ 041.get { return _addEditButtonString; } 042.set 043.{ 044.if (_addEditButtonString != value) 045.{ 046._addEditButtonString = value; 047.NotifyChanged("AddEditButtonString"); 048.} 049.} 050.} 051. 052.public SubscriptionToken addJobToken = new SubscriptionToken(); 053.public SubscriptionToken editJobToken = new SubscriptionToken(); 054. 055.public DelegateCommand<object> AddEditCommand { get; set; } 056.public DelegateCommand<object> CancelCommand { get; set; } 057. 058.private ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); 059.public ObservableCollection<ValidationError> Errors 060.{ 061.get { return _errors; } 062.} 063. 064.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 065.public ObservableCollection<ValidationResult> ValResults 066.{ 067.get { return this._valResults; } 068.} 069. 070.public AddEditJobViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 071.{ 072.// set Unity items 073.this.eventAggregator = eventAgg; 074.this.regionManager = regionmanager; 075. 076.context = new RecruitingContext(); 077. 078.AddEditCommand = new DelegateCommand<object>(this.AddEditJobCommand); 079.CancelCommand = new DelegateCommand<object>(this.CancelAddEditCommand); 080. 081.SetSubscriptions(); 082.} 083. 084.#region Subscription Declaration and Events 085. 086.public void SetSubscriptions() 087.{ 088.AddJobEvent addJob = this.eventAggregator.GetEvent<AddJobEvent>(); 089. 090.if (addJobToken != null) 091.addJob.Unsubscribe(addJobToken); 092. 093.addJobToken = addJob.Subscribe(this.AddJobEventHandler); 094. 095.EditJobEvent editJob = this.eventAggregator.GetEvent<EditJobEvent>(); 096. 097.if (editJobToken != null) 098.editJob.Unsubscribe(editJobToken); 099. 100.editJobToken = editJob.Subscribe(this.EditJobEventHandler); 101.} 102. 103.public void AddJobEventHandler(bool isNew) 104.{ 105.this.activeJob = null; 106.this.activeJob = new JobPosting(); 107.this.activeJob.IsActive = true; // We assume that we want a new job to go up immediately 108.this.isNewJob = true; 109.this.AddEditString = "Add New Job Posting"; 110.this.AddEditButtonString = "Add Job"; 111. 112.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 113.} 114. 115.public void EditJobEventHandler(JobPosting editJob) 116.{ 117.this.activeJob = null; 118.this.activeJob = editJob; 119.this.isNewJob = false; 120.this.AddEditString = "Edit Job Posting"; 121.this.AddEditButtonString = "Edit Job"; 122. 123.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 124.} 125. 126.#endregion 127. 128.#region DelegateCommands from View 129. 130.public void AddEditJobCommand(object obj) 131.{ 132.if (this.Errors.Count > 0) 133.{ 134.List<string> errorMessages = new List<string>(); 135. 136.foreach (var valR in this.Errors) 137.{ 138.errorMessages.Add(valR.Exception.Message); 139.} 140. 141.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 142. 143.} 144.else if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 145.{ 146.List<string> errorMessages = new List<string>(); 147. 148.foreach (var valR in this._valResults) 149.{ 150.errorMessages.Add(valR.ErrorMessage); 151.} 152. 153.this._valResults.Clear(); 154. 155.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 156.} 157.else 158.{ 159.if (this.isNewJob) 160.{ 161.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(this.activeJob); 162.} 163.else 164.{ 165.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(true); 166.} 167.} 168.} 169. 170.public void CancelAddEditCommand(object obj) 171.{ 172.if (this.isNewJob) 173.{ 174.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(null); 175.} 176.else 177.{ 178.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(false); 179.} 180.} 181. 182.#endregion 183.} 184.} We start seeing something new on line 103- the AddJobEventHandler will create a new job and set that to the activeJob item on the ViewModel. When this is all set, the view calls that familiar MakeMeActive method to activate itself. I made a bit of a management call on making views self-activate like this, but I figured it works for one reason. As I create this application, views may not exist that I have in mind, so after a view receives its 'ping' from being subscribed to an event, it prepares whatever it needs to do and then goes active. This way if I don't have 'edit' hooked up, I can click as the day is long on the main view and won't get lost in an empty region. Total personal preference here. :) Everything else should again be pretty straightforward, although I do a bit of validation checking in the AddEditJobCommand, which can either fire off an event back to the main view/viewmodel if everything is a success or sent a list of errors to our notification module, which pops open a RadWindow with the alerts if any exist. As a bonus side note, here's what my WCF RIA Services metadata looks like for handling all of the validation: private JobPostingMetadata() { } [StringLength(2500, ErrorMessage = "Description should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage = "Description is required.")] public string Description; [Required(ErrorMessage="Active Status is Required")] public bool IsActive; [StringLength(100, ErrorMessage = "Posting title must be more than 3 but less than 100 characters.", MinimumLength = 3)] [Required(ErrorMessage = "Job Title is required.")] public bool JobTitle; [Required] public string Location; public bool NeedsCV; public bool NeedsOverview; public bool NeedsResume; public int PostingID; [Required(ErrorMessage="Qualifications are required.")] [StringLength(2500, ErrorMessage="Qualifications should be more than one and less than 2500 characters.", MinimumLength=1)] public string Qualifications; [StringLength(2500, ErrorMessage = "Requirements should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage="Requirements are required.")] public string Requirements;   The RecruitCB Alternative See all that Xaml I pasted above? Those are now two pieces sitting in the JobsView.xaml file now. The only real difference is that the xEditGrid now sits in the same place as xJobsGrid, with visibility swapping out between the two for a quick switch. I also took out all the cal: and command: command references and replaced Button events with clicks and the Grid selection command replaced with a SelectedItemChanged event. Also, at the bottom of the xEditGrid after the last button, I add a ValidationSummary (with Visibility=Collapsed) to catch any errors that are popping up. Simple as can be, and leads to this being the single code-behind file: 001.public partial class JobsView : UserControl 002.{ 003.public RecruitingContext context; 004.public JobPosting activeJob; 005.public bool isNew; 006.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 007.public ObservableCollection<ValidationResult> ValResults 008.{ 009.get { return this._valResults; } 010.} 011.public JobsView() 012.{ 013.InitializeComponent(); 014.this.Loaded += new RoutedEventHandler(JobsView_Loaded); 015.} 016.void JobsView_Loaded(object sender, RoutedEventArgs e) 017.{ 018.context = new RecruitingContext(); 019.xJobsGrid.ItemsSource = context.JobPostings; 020.context.Load(context.GetJobPostingsQuery()); 021.} 022.private void xAddRecordButton_Click(object sender, RoutedEventArgs e) 023.{ 024.activeJob = new JobPosting(); 025.isNew = true; 026.xAddEditTitle.Text = "Add a Job Posting"; 027.xAddEditButton.Content = "Add"; 028.xEditGrid.DataContext = activeJob; 029.HideJobsGrid(); 030.} 031.private void xEditRecordButton_Click(object sender, RoutedEventArgs e) 032.{ 033.activeJob = xJobsGrid.SelectedItem as JobPosting; 034.isNew = false; 035.xAddEditTitle.Text = "Edit a Job Posting"; 036.xAddEditButton.Content = "Edit"; 037.xEditGrid.DataContext = activeJob; 038.HideJobsGrid(); 039.} 040.private void xAddEditButton_Click(object sender, RoutedEventArgs e) 041.{ 042.if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 043.{ 044.List<string> errorMessages = new List<string>(); 045.foreach (var valR in this._valResults) 046.{ 047.errorMessages.Add(valR.ErrorMessage); 048.} 049.this._valResults.Clear(); 050.ShowErrors(errorMessages); 051.} 052.else if (xSummary.Errors.Count > 0) 053.{ 054.List<string> errorMessages = new List<string>(); 055.foreach (var err in xSummary.Errors) 056.{ 057.errorMessages.Add(err.Message); 058.} 059.ShowErrors(errorMessages); 060.} 061.else 062.{ 063.if (this.isNew) 064.{ 065.context.JobPostings.Add(activeJob); 066.context.SubmitChanges((s) => 067.{ 068.ActionHistory thisAction = new ActionHistory(); 069.thisAction.PostingID = activeJob.PostingID; 070.thisAction.Description = String.Format("Job '{0}' has been edited by {1}", activeJob.JobTitle, "default user"); 071.thisAction.TimeStamp = DateTime.Now; 072.context.ActionHistories.Add(thisAction); 073.context.SubmitChanges(); 074.}, null); 075.} 076.else 077.{ 078.context.SubmitChanges((s) => 079.{ 080.ActionHistory thisAction = new ActionHistory(); 081.thisAction.PostingID = activeJob.PostingID; 082.thisAction.Description = String.Format("Job '{0}' has been added by {1}", activeJob.JobTitle, "default user"); 083.thisAction.TimeStamp = DateTime.Now; 084.context.ActionHistories.Add(thisAction); 085.context.SubmitChanges(); 086.}, null); 087.} 088.ShowJobsGrid(); 089.} 090.} 091.private void xCancelButton_Click(object sender, RoutedEventArgs e) 092.{ 093.ShowJobsGrid(); 094.} 095.private void ShowJobsGrid() 096.{ 097.xAddEditRecordButtonPanel.Visibility = Visibility.Visible; 098.xEditGrid.Visibility = Visibility.Collapsed; 099.xJobsGrid.Visibility = Visibility.Visible; 100.} 101.private void HideJobsGrid() 102.{ 103.xAddEditRecordButtonPanel.Visibility = Visibility.Collapsed; 104.xJobsGrid.Visibility = Visibility.Collapsed; 105.xEditGrid.Visibility = Visibility.Visible; 106.} 107.private void ShowErrors(List<string> errorList) 108.{ 109.string nm = "Errors received: \n"; 110.foreach (string anerror in errorList) 111.nm += anerror + "\n"; 112.RadWindow.Alert(nm); 113.} 114.} The first 39 lines should be pretty familiar, not doing anything too unorthodox to get this up and running. Once we hit the xAddEditButton_Click on line 40, we're still doing pretty much the same things except instead of checking the ValidationHelper errors, we both run a check on the current activeJob object as well as check the ValidationSummary errors list. Once that is set, we again use the callback of context.SubmitChanges (lines 68 and 78) to create an ActionHistory which we will use to track these items down the line. That's all? Essentially... yes. If you look back through this post, most of the code and adventures we have taken were just to get things working in the MVVM/Prism setup. Since I have the whole 'module' self-contained in a single JobView+code-behind setup, I don't have to worry about things like sending events off into space for someone to pick up, communicating through an Infrastructure project, or even re-inventing events to be used with attached behaviors. Everything just kinda works, and again with much less code. Here's a picture of the MVVM and Code-behind versions on the Jobs and AddEdit views, but since the functionality is the same in both apps you still cannot tell them apart (for two-strike): Looking ahead, the Applicants module is effectively the same thing as the Jobs module, so most of the code is being cut-and-pasted back and forth with minor tweaks here and there. So that one is being taken care of by me behind the scenes. Next time, we get into a new world of fun- the interview scheduling module, which will pull from available jobs and applicants for each interview being scheduled, tying everything together with RadScheduler to the rescue. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • WPF: DataGrid Cell Double-click

    - by Jonathan Allen
    Is there a better way than this to determine the row a user double-clicked on in a data-grid? Private Sub ResultsGrid_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Dim node As DependencyObject = CType(e.OriginalSource, DependencyObject) Do Until TypeOf node Is Microsoft.Windows.Controls.DataGridRow OrElse node Is Nothing node = VisualTreeHelper.GetParent(node) Loop If node IsNot Nothing Then Dim data = CType((CType(node, Microsoft.Windows.Controls.DataGridRow)).DataContext, Customer) 'do something End If End Sub

    Read the article

  • Why does ObservableCollection throws an exception when being modified?

    - by Oliver Hanappi
    Hi! My application uses a WPF DataGrid. One of the columns is a template column that containts a combobox bound to an ObservableCollection of the entity which feeds the row. When I add a value to the ObservableCollection, a NullReferenceException is thrown. Has anybody an idea why this happens? Here is the stacktrace of the exception: at MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid() at MS.Internal.Data.PropertyPathWorker.get_IsDBNullValidForUpdate() at MS.Internal.Data.ClrBindingWorker.get_IsDBNullValidForUpdate() at System.Windows.Data.BindingExpression.ConvertProposedValue(Object value) at System.Windows.Data.BindingExpressionBase.UpdateValue() at System.Windows.Data.BindingExpression.Update(Boolean synchronous) at System.Windows.Data.BindingExpressionBase.Dirty() at System.Windows.Data.BindingExpression.SetValue(DependencyObject d, DependencyProperty dp, Object value) at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties() at System.Windows.Controls.Primitives.Selector.SelectionChanger.End() at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e) at System.Windows.Controls.ItemsControl.OnItemCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Controls.ItemCollection.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e) at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex) at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Add(T item) at ORF.PersonBook.IdentityModule.Model.SubsidiaryModel.AddRoom(RoomModel room) in C:\Project\Phoenix\Development\src\ORF.PersonBook.IdentityModule\Model\SubsidiaryModel.cs:line 127

    Read the article

  • MVVM- How can I bind to a property, which is not a DependancyProperty?

    - by highone
    I have found this question http://stackoverflow.com/questions/2245928/mvvm-and-the-textboxs-selectedtext-property. However, I am having trouble getting the solution given to work. This is my non-working code: View: SelectedText and Text are just string properties from my ViewModel. <TextBox Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" Height="155" HorizontalAlignment="Left" Margin="68,31,0,0" Name="textBox1" VerticalAlignment="Top" Width="264" AcceptsReturn="True" AcceptsTab="True" local:TextBoxHelper.SelectedText="{Binding SelectedText, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding SelectedText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Height="154" HorizontalAlignment="Left" Margin="82,287,0,0" Name="textBox2" VerticalAlignment="Top" Width="239" /> TextBoxHelper public static class TextBoxHelper { #region "Selected Text" public static string GetSelectedText(DependencyObject obj) { return (string)obj.GetValue(SelectedTextProperty); } public static void SetSelectedText(DependencyObject obj, string value) { obj.SetValue(SelectedTextProperty, value); } // Using a DependencyProperty as the backing store for SelectedText. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.RegisterAttached( "SelectedText", typeof(string), typeof(TextBoxHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedTextChanged)); private static void SelectedTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { TextBox tb = obj as TextBox; if (tb != null) { if (e.OldValue == null && e.NewValue != null) { tb.SelectionChanged += tb_SelectionChanged; } else if (e.OldValue != null && e.NewValue == null) { tb.SelectionChanged -= tb_SelectionChanged; } string newValue = e.NewValue as string; if (newValue != null && newValue != tb.SelectedText) { tb.SelectedText = newValue as string; } } } static void tb_SelectionChanged(object sender, RoutedEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { SetSelectedText(tb, tb.SelectedText); } } #endregion } What am I doing wrong?

    Read the article

  • WPF Data Binding won't work

    - by Tokk
    Hey, I have got an UserControll with a DependencyProperty called "Risikobewertung" whitch has the own Datatype "RisikoBewertung"(Datatype created by LINQ). So in my Controll I try to bind the Fields of RisikoBewertung to the TextBoxes on the Controll, but It won't work. I hope you can help me, and tell me why ;) Code: UserControl.xaml: <UserControl x:Class="Cis.Modules.RiskManagement.Views.Controls.RisikoBewertungEditor" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:gridtools="clr-namespace:TmgUnity.Common.Presentation.Controls.DataGridTools;assembly=TmgUnity.Common.Presentation" xmlns:converter="clr-namespace:Cis.Modules.RiskManagement.Views.Converter" xmlns:tmg="clr-namespace:TmgUnity.Common.Presentation.Controls.FilterDataGrid;assembly=TmgUnity.Common.Presentation" xmlns:validators="clr-namespace:TmgUnity.Common.Presentation.ValidationRules;assembly=TmgUnity.Common.Presentation" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:risikoControls="clr-namespace:Cis.Modules.RiskManagement.Views.Controls"> <UserControl.Resources> <converter:CountToArrowConverter x:Key="CountConverter" /> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Name="Veränderung"/> <ColumnDefinition Name="Volumen" /> <ColumnDefinition Name="Schadenshöhe" /> <ColumnDefinition Name="SchadensOrte" /> <ColumnDefinition Name="Wahrscheinlichkeit" /> <ColumnDefinition Name="Kategorie" /> <ColumnDefinition Name="Handlungsbedarf" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Image Source="{Binding Path=Entwicklung, Converter={StaticResource CountConverter}, UpdateSourceTrigger=PropertyChanged}" Grid.RowSpan="2" Grid.Row="0" Width="68" Height="68" Grid.Column="0" /> <TextBox Grid.Column="1" Grid.Row="0" Text="Volumen" /> <TextBox Grid.Column="1" Grid.Row="1"> <TextBox.Text> <Binding Path="Volumen" UpdateSourceTrigger="PropertyChanged" /> </TextBox.Text> </TextBox> <TextBox Grid.Column="2" Grid.Row="0" Text="Schadenshöhe" /> <TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Schadenshöhe, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="3" Grid.RowSpan="2" Grid.Row="0" Orientation="Horizontal"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBox Text ="Politik" Grid.Row="0" Grid.Column="0"/> <CheckBox Name="Politik" Grid.Row="1" Grid.Column="0" IsChecked="{Binding Path=Politik, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vermögen" Grid.Row="0" Grid.Column="1" /> <CheckBox Name="Vermögen" Grid.Row="1" Grid.Column="1" IsChecked="{Binding Path=Vermögen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vertrauen" Grid.Row="0" Grid.Column="2" /> <CheckBox Name="Vertrauen" Grid.Row="1" Grid.Column="2" IsChecked="{Binding Path=Vertrauen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> </Grid> </StackPanel> <TextBox Grid.Column="4" Grid.Row="0" Text="Wahrscheinlichkeit" /> <TextBox Grid.Column="4" Grid.Row="1" Text="{Binding Path=Wahrscheinlichkeit, UpdateSourceTrigger=PropertyChanged}"/> <risikoControls:RiskTrafficLightControl Grid.Column="5" Grid.Row="0" Grid.RowSpan="2" RiskValue="{Binding Path=Kategorie, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="6" Grid.RowSpan="2" Grid.Row="0" Orientation="Vertical"> <TextBox Text="Handlungsbedarf" /> <CheckBox VerticalAlignment="Center" HorizontalAlignment="Center" IsChecked="{Binding Path=Handlungsbedarf, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel> </Grid> The CodeBehind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using Cis.Modules.RiskManagement.Data; using Cis.Modules.RiskManagement.Views.Models; namespace Cis.Modules.RiskManagement.Views.Controls { /// <summary> /// Interaktionslogik für RisikoBewertungEditor.xaml /// </summary> public partial class RisikoBewertungEditor : UserControl, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty RisikoBewertungProperty = DependencyProperty.Register("RisikoBewertung", typeof(RisikoBewertung), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(RisikoBewertungChanged))); // public static readonly DependencyProperty Readonly = DependencyProperty.Register("EditorReadonly", typeof(Boolean), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(ReadonlyChanged))); private static void RisikoBewertungChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { var bewertungEditor = dependencyObject as RisikoBewertungEditor; bewertungEditor.RisikoBewertung = arguments.NewValue as RisikoBewertung; } /* private static void ReadonlyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { } */ public RisikoBewertung RisikoBewertung { get { return GetValue(RisikoBewertungProperty) as RisikoBewertung; } set { SetValue(RisikoBewertungProperty, value); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("RisikoBewertung")); } } } /* public Boolean EditorReadonly { get; set; } */ public void mebosho(object sender, RoutedEventArgs e) { MessageBox.Show(RisikoBewertung.LfdNr.ToString()); } public RisikoBewertungEditor() { InitializeComponent(); RisikoBewertung = new RisikoBewertung(); this.DataContext = (GetValue(RisikoBewertungProperty) as RisikoBewertung); } } } and a little example of it's usage: <tmg:FilterDataGrid Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding TodoListe}" IsReadOnly="False" x:Name="TodoListeDataGrid" CanUserAddRows="False" SelectionUnit="FullRow" SelectedValuePath="." SelectedValue="{Binding CurrentTodoItem}" gridtools:DataGridStyle.SelectAllButtonTemplate="{DynamicResource CisSelectAllButtonTemplate}" CanUserResizeColumns="True" MinHeight="80" SelectionChanged="SelectionChanged" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" diagnostics:PresentationTraceSources.TraceLevel="High" > <tmg:FilterDataGrid.RowDetailsTemplate> <DataTemplate> <risikoControls:RisikoBewertungEditor x:Name="BewertungEditor" RisikoBewertung="{Binding ElementName=TodoListeDataGrid, Path=SelectedValue}" diagnostics:PresentationTraceSources.TraceLevel="High"> </risikoControls:RisikoBewertungEditor> </DataTemplate> </tmg:FilterDataGrid.RowDetailsTemplate> <tmg:FilterDataGrid.Columns> <toolkit:DataGridTextColumn Binding="{Binding Path=LfdNr}" Header="LfdNr" /> </tmg:FilterDataGrid.Columns> </tmg:FilterDataGrid>

    Read the article

  • Bing maps silverlight control custom pushpin

    - by Razvi
    I tried to make a custom pushpin for the Bing Maps silverlight control, but I can only add 1 pushpin. At the second pushpin I get the following error: System.ArgumentException: Value does not fall within the expected range. at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.Collection_AddValue[T](PresentationFrameworkCollection`1 collection, CValue value) at MS.Internal.XcpImports.Collection_AddDependencyObject[T](PresentationFrameworkCollection`1 collection, DependencyObject value) at System.Windows.PresentationFrameworkCollection`1.AddDependencyObject(DependencyObject value) at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value) at System.Windows.PresentationFrameworkCollection`1.Add(T value) at MapInfo.Silverlight.CitiesControl.MainPage.c_GetCitiesCompleted(Object sender, GetCitiesCompletedEventArgs e) Does anyone know what I might be doing wrong? I am setting the following properties before adding it to the map: public Location Location { get { return this.GetValue(MapLayer.PositionProperty) as Location; } set { this.SetValue(MapLayer.PositionProperty, value); } } this.SetValue(MapLayer.PositionOriginProperty, PositionOrigin.BottomLeft);

    Read the article

  • WPF: how to find an element in a datatemplate from an itemscontrol

    - by EV
    Hi, I have the following problem: the application is using the custom itemscontrol called ToolBox. The elements of a toolbox are called toolboxitems and are custom contentcontrol. Now, the toolbox stores a number of images that are retrieved from a database and displayed. For that I use a datatemplate inside the toolbox control. However, when I try to drag and drop the elements, I don't get the image object but the database component. I thought that I should then traverse the structure to find the Image element. here's the code: Toolbox: public class Toolbox : ItemsControl { private Size defaultItemSize = new Size(65, 65); public Size DefaultItemSize { get { return this.defaultItemSize; } set { this.defaultItemSize = value; } } protected override DependencyObject GetContainerForItemOverride() { return new ToolboxItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return (item is ToolboxItem); } } ToolBoxItem: public class ToolboxItem : ContentControl { private Point? dragStartPoint = null; static ToolboxItem() { FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem), new FrameworkPropertyMetadata(typeof(ToolboxItem))); } protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { base.OnPreviewMouseDown(e); this.dragStartPoint = new Point?(e.GetPosition(this)); } public String url { get; private set; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton != MouseButtonState.Pressed) { this.dragStartPoint = null; } if (this.dragStartPoint.HasValue) { Point position = e.GetPosition(this); if ((SystemParameters.MinimumHorizontalDragDistance <= Math.Abs((double)(position.X - this.dragStartPoint.Value.X))) || (SystemParameters.MinimumVerticalDragDistance <= Math.Abs((double)(position.Y - this.dragStartPoint.Value.Y)))) { string xamlString = XamlWriter.Save(this.Content); MessageBoxResult result = MessageBox.Show(xamlString); DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString); if (dataObject != null) { DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy); } } e.Handled = true; } } private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; } } here is the xaml file for ToolBox and toolbox item: <Style TargetType="{x:Type s:ToolboxItem}"> <Setter Property="Control.Padding" Value="5" /> <Setter Property="ContentControl.HorizontalContentAlignment" Value="Stretch" /> <Setter Property="ContentControl.VerticalContentAlignment" Value="Stretch" /> <Setter Property="ToolTip" Value="{Binding ToolTip}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type s:ToolboxItem}"> <Grid> <Rectangle Name="Border" StrokeThickness="1" StrokeDashArray="2" Fill="Transparent" SnapsToDevicePixels="true" /> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" ContentTemplate="{TemplateBinding ContentTemplate}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Stroke" Value="Gray" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type s:Toolbox}"> <Setter Property="SnapsToDevicePixels" Value="true" /> <Setter Property="Focusable" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" SnapsToDevicePixels="True"> <ScrollViewer VerticalScrollBarVisibility="Auto"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <WrapPanel Margin="0,5,0,5" ItemHeight="{Binding Path=DefaultItemSize.Height, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" ItemWidth="{Binding Path=DefaultItemSize.Width, RelativeSource={RelativeSource AncestorType=s:Toolbox}}" /> </ItemsPanelTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> Example usage: <Toolbox x:Name="NewLibrary" DefaultItemSize="55,55" ItemsSource="{Binding}" > <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <Image Source="{Binding Path=url}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </Toolbox> The object that I get is a database object. When using a static resource I get the Image object. How to retrieve this Image object from a datatemplate? I though that I could use this tutorial: http://msdn.microsoft.com/en-us/library/bb613579.aspx But it does not seem to solve the problem. Could anyone suggest a solution? Thanks!

    Read the article

  • Element is already the child of another element.

    - by Erica
    I get the folowing error in my Silverlight application. But i cant figure out what control it is that is the problem. If i debug it don't break on anything in the code, it just fails in this framework callstack with only framework code. Is there any way to get more information on what part of a Silverlight app that is the problem in this case. Message: Sys.InvalidOperationException: ManagedRuntimeError error #4004 in control 'Xaml1': System.InvalidOperationException: Element is already the child of another element. at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.Collection_AddValue[T](PresentationFrameworkCollection1 collection, CValue value) at MS.Internal.XcpImports.Collection_AddDependencyObject[T](PresentationFrameworkCollection1 collection, DependencyObject value) at System.Windows.PresentationFrameworkCollection1.AddDependencyObject(DependencyObject value) at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value) at System.Windows.PresentationFrameworkCollection1.Add(T value) at System.Windows.Controls.AutoCompleteBox.OnApplyTemplate() at System.Windows.FrameworkElement.OnApplyTemplate(IntPtr nativeTarget)

    Read the article

1 2 3 4 5  | Next Page >