Search Results

Search found 854 results on 35 pages for 'databinding'.

Page 10/35 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • WPF binding ComboBox to enum (with a twist)

    - by Carlo
    Well the problem is that I have this enum, BUT I don't want the combobox to show the values of the enum. This is the enum: public enum Mode { [Description("Display active only")] Active, [Description("Display selected only")] Selected, [Description("Display active and selected")] ActiveAndSelected } So in the ComboBox instead of displaying Active, Selected or ActiveAndSelected, I want to display the DescriptionProperty for each value of the enum. I do have an extension method called GetDescription() for the enum: public static string GetDescription(this Enum enumObj) { FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString()); object[] attribArray = fieldInfo.GetCustomAttributes(false); if (attribArray.Length == 0) { return enumObj.ToString(); } else { DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute; return attrib.Description; } } So is there a way I can bind the enum to the ComboBox AND show it's content with the GetDescription extension method? Thanks!

    Read the article

  • Why does WPF Style to show validation errors in ToolTip work for a TextBox but fails for a ComboBox?

    - by Mike B
    I am using a typical Style to display validation errors as a tooltip from IErrorDataInfo for a textbox as shown below and it works fine. <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> But when i try to do the same thing for a ComboBox like this it fails <Style TargetType="{x:Type ComboBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> The error I get in the output window is: System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'ValidationError') from '(Validation.Errors)' (type 'ReadOnlyObservableCollection`1'). BindingExpression:Path=(0)[0].ErrorContent; DataItem='ComboBox' (Name='ownerComboBox'); target element is 'ComboBox' (Name='ownerComboBox'); target property is 'ToolTip' (type 'Object') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.Parameter name: index' Oddly it also attempts to make invalid Database changes when I close the window if I change any ComboBox values (This is also when the binding error occurs)!!! Cannot insert the value NULL into column 'EmpFirstName', table 'OITaskManager.dbo.Employees'; column does not allow nulls. INSERT fails. The statement has been terminated. Simply by commenting the style out everyting works perfectly. How do I fix this? Just in case anyone needs it one of the comboBox' xaml follows: <ComboBox ItemsSource="{Binding Path=Employees}" SelectedValuePath="EmpID" SelectedValue="{Binding Path=SelectedIssue.Employee2.EmpID, Mode=OneWay, ValidatesOnDataErrors=True}" ItemTemplate="{StaticResource LastNameFirstComboBoxTemplate}" Height="28" Name="ownerComboBox" Width="120" Margin="2" SelectionChanged="ownerComboBox_SelectionChanged" /> <DataTemplate x:Key="LastNameFirstComboBoxTemplate"> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{1}, {0}" > <Binding Path="EmpFirstName" /> <Binding Path="EmpLastName" /> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> SelectionChanged: (I do plan to implement commanding before long but, as this is my first WPF project I have not gone full MVVM yet. I am trying to take things in small-medium sized bites) // This is done this way to maintain the DataContext Integrity // and avoid an error due to an Object being "Not New" in Linq-to-SQL private void ownerComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { Employee currentEmpl = ownerComboBox.SelectedItem as Employee; if (currentEmpl != null && currentEmpl != statusBoardViewModel.SelectedIssue.Employee2) { statusBoardViewModel.SelectedIssue.Employee2 = currentEmpl; } }

    Read the article

  • How to bind a datatable to a wpf editable combobox: selectedItem showing System.Data.DataRowView

    - by black sensei
    Hello Good People!! I bound a datatable to a combobox and defined a dataTemplate in the itemTemplate.i can see desired values in the combobox dropdown list,what i see in the selectedItem is System.Data.DataRowView here are my codes: <ComboBox Margin="128,139,123,0" Name="cmbEmail" Height="23" VerticalAlignment="Top" TabIndex="1" ToolTip="enter the email you signed up with here" IsEditable="True" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=username}"/> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> The code behind is so : if (con != null) { con.Open(); //users table has columns id | username | pass SQLiteCommand cmd = new SQLiteCommand("select * from users", con); SQLiteDataAdapter da = new SQLiteDataAdapter(cmd); userdt = new DataTable("users"); da.Fill(userdt); cmbEmail.DataContext = userdt; } I've been looking for something like SelectedValueTemplate or SelectedItemTemplate to do the same kind of data templating but i found none. I'll like to ask if i'm doing something wrong or it's a known issue for combobox binding? if something is wrong in my code please point me to the right direction. thanks for reading this

    Read the article

  • Alternative to FindAncestor RelativeSource in Silverlight 4 to bind to a property of the page

    - by TimothyP
    Hi, FindAncestor RelativeSource only supports 'Self' and 'TemplatedParent', but I have to bind the width of a popup to the width of the page. Giving the page a name causes problems because sometimes it will throw exceptions saying a control with that name is already present in the visual tree. <Popup IsOpen="True" Width="{Binding ElementName=BordPage, Path=Width}" Height="{Binding ElementName=BordPage, Path=Height}"> Background information: I'm using a SL4 navigation based application here. BordPage is a navigation page, which I'm using multiple times within the application. So giving it a name in the page itself is not really a good idea, but I don't know how else I can bind to the width and height of the page. What I'm trying to do is have a black border (with opacity 0.8) cover the entire screen, (including the controls of the MainPage). Then on top of that I want to display some other controls. Since the application is touch controlled, providing the user with a ComboBox to select a value doesn't really work wel. Instead I want to show this black overlay window with a listbox taking up most of the screen so the user can simply touch the value he wants with a single click. Update: I just realized I can use the ChildWindow class to do this. But my original question remains.

    Read the article

  • WPF animation: binding to the "To" attribute of storyboard animation.

    - by bozalina
    Hi, I'm trying to create a button that behaves similarly to the "slide" button on the iPhone. I have an animation that adjusts the position and width of the button, but I want these values to be based on the text used in the control. Currently, they're hardcoded. Here's my working XAML, so far: <CheckBox x:Class="Smt.Controls.SlideCheckBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Smt.Controls" xmlns:System.Windows="clr-namespace:System.Windows;assembly=PresentationCore" Name="SliderCheckBox" mc:Ignorable="d"> <CheckBox.Resources> <System.Windows:Duration x:Key="AnimationTime">0:0:0.2</System.Windows:Duration> <Storyboard x:Key="OnChecking"> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)" Duration="{StaticResource AnimationTime}" To="40" /> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="41" /> </Storyboard> <Storyboard x:Key="OnUnchecking"> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)" Duration="{StaticResource AnimationTime}" To="0" /> <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="40" /> </Storyboard> <Style x:Key="SlideCheckBoxStyle" TargetType="{x:Type local:SlideCheckBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:SlideCheckBox}"> <Canvas> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" RecognizesAccessKey="True" VerticalAlignment="Center" HorizontalAlignment="Center" /> <Canvas> <!--Background--> <Rectangle Width="{Binding ElementName=ButtonText, Path=ActualWidth}" Height="{Binding ElementName=ButtonText, Path=ActualHeight}" Fill="LightBlue" /> </Canvas> <Canvas> <!--Button--> <Button Width="{Binding ElementName=CheckedText, Path=ActualWidth}" Height="{Binding ElementName=ButtonText, Path=ActualHeight}" Name="CheckButton" Command="{x:Static local:SlideCheckBox.SlideCheckBoxClicked}"> <Button.RenderTransform> <TransformGroup> <TranslateTransform /> </TransformGroup> </Button.RenderTransform> </Button> </Canvas> <Canvas> <!--Text--> <StackPanel Name="ButtonText" Orientation="Horizontal" IsHitTestVisible="False"> <Grid Name="CheckedText"> <Label Margin="7 0" Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:SlideCheckBox}}, Path=CheckedText}" /> </Grid> <Grid Name="UncheckedText" HorizontalAlignment="Right"> <Label Margin="7 0" Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:SlideCheckBox}}, Path=UncheckedText}" /> </Grid> </StackPanel> </Canvas> </Canvas> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource OnChecking}" /> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource OnUnchecking}" /> </Trigger.ExitActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </CheckBox.Resources> <CheckBox.CommandBindings> <CommandBinding Command="{x:Static local:SlideCheckBox.SlideCheckBoxClicked}" Executed="OnSlideCheckBoxClicked" /> </CheckBox.CommandBindings> </CheckBox> And the code behind: using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Smt.Controls { public partial class SlideCheckBox : CheckBox { public SlideCheckBox() { InitializeComponent(); Loaded += OnLoaded; } public static readonly DependencyProperty CheckedTextProperty = DependencyProperty.Register("CheckedText", typeof(string), typeof(SlideCheckBox), new PropertyMetadata("Checked Text")); public string CheckedText { get { return (string)GetValue(CheckedTextProperty); } set { SetValue(CheckedTextProperty, value); } } public static readonly DependencyProperty UncheckedTextProperty = DependencyProperty.Register("UncheckedText", typeof(string), typeof(SlideCheckBox), new PropertyMetadata("Unchecked Text")); public string UncheckedText { get { return (string)GetValue(UncheckedTextProperty); } set { SetValue(UncheckedTextProperty, value); } } public static readonly RoutedCommand SlideCheckBoxClicked = new RoutedCommand(); void OnLoaded(object sender, RoutedEventArgs e) { Style style = TryFindResource("SlideCheckBoxStyle") as Style; if (!ReferenceEquals(style, null)) { Style = style; } } void OnSlideCheckBoxClicked(object sender, ExecutedRoutedEventArgs e) { IsChecked = !IsChecked; } } } The problem comes when I try to bind the "To" attribute in the DoubleAnimations to the actual width of the text, the same as I'm doing in the ControlTemplate. If I bind the values to an ActualWidth of an element in the ControlTemplate, the control comes up as a blank checkbox (my base class). However, I'm binding to the same ActualWidths in the ControlTemplate itself without any problems. Just seems to be the CheckBox.Resources that have a problem with it. For instance, the following will break it: <DoubleAnimation Storyboard.TargetName="CheckButton" Storyboard.TargetProperty="(Button.Width)" Duration="{StaticResource AnimationTime}" To="{Binding ElementName=CheckedText, Path=ActualWidth}" /> I don't know whether this is because it's trying to bind to a value that doesn't exist until a render pass is done, or if it's something else. Anyone have any experience with this sort of animation binding?

    Read the article

  • WPF Debugging AvalonEdit binding to Document property.

    - by kubal5003
    Hello, all day long I am sitting and trying to find out why binding to AvalonEdits Document property isn't working. AvalonEdit is an advanced WPF text editor - part of the SharpDevelop project.(it's going to be used in SharpDevelop v4 Mirador). So when I set up a simple project - one TextEditor (that's the AvalonEdits real name in the library) and made a simple class that has one property - Document and it returns a dummy object with some static text the binding is working perfectly. However in real life solution I'm binding a collection of SomeEditor objects to TabControl. TabControl has DataTemplate for SomeEditor and there's the TextEditor object. <TabControl Grid.Column="1" x:Name="tabControlFiles" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" > <TabControl.Resources> <DataTemplate DataType="{x:Type m:SomeEditor}"> <a:TextEditor Document="{Binding Path=Document, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NoopConverter}, IsAsync=True}" x:Name="avalonEdit"></a:TextEditor> </DataTemplate> </TabControl.Resources> <TabControl.ItemContainerStyle> <Style BasedOn="{StaticResource TabItemStyle}" TargetType="{x:Type TabItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected}"></Setter> </Style> </TabControl.ItemContainerStyle> </TabControl> This doesn't work. What I've investigated so far: DataContext of TextEditor is set to the proper instance of SomeEditor TextEditors Document property is set to some other instance than SomeEditor.Document property when I set breakpoint to no-op converter that is attached to that binding it shows me the correct value for Document (the converter is used!) I also dug through the VisualTree to obtain reference to TextEditor and called GetBindingExpression(TextEditor.DocumentProperty) and this did return nothing WPF produces the following information: System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Document; DataItem='SomeEditor' (HashCode=26280264); target element is 'TextEditor' (Name='avalonEdit'); target property is 'Document' (type 'TextDocument') SomeEditor instance that is bound to already has a created and cached copy of Document before the binding occurs. The getter is never called. Anyone can tell me what might be wrong? Why BindingExpression isn't set ? Why property getter is never called?

    Read the article

  • WPF - Binding an ObservableCollection Dependency Property within a UserControl

    - by John
    I have a control class DragGrid : Grid { ... } which inherits from the original grid and enables dragging and resizing its child elements. I need to bind a custom DP named WorkItemsProperty to an observable collection of type WorkItem (implements INotifyPropertyChanged). Each element in the grid is bound to a collection item. Whenever the user adds a new item dynamically at runtime (the items cannot be declared in XAML!), or deletes an item from that collection, the WorkItems DP on the DragGrid should be updated, and the children in the grid (where each child represents a WorkItem collection item). My question is how does the DP notify the control about which child element in the grid must be removed, changed ('change' means user dragged an element, or resized it with the mouse) or added, and how would I identify which one of the existing children is the one that needs to be deleted or changed. I understand that this is where the DependencyPropertyChangedCallback comes in. But that only gets called when the DP property is set anew, not when something inside the collection changes (like add, remove item). So in the end, does the DragGrid control somehow need to subscribe to the CollectionChanged event? At what point would I hook up the event handler for that?

    Read the article

  • how to bind datasouce to the labels and pass parameter in XtraReport ?

    - by ahmed
    There's something that I don't get it yet in Xtrareport. I have to bind the datasource at runtime and also I have to assign the datasource to the labels programatically. Binding data at runtime is fine ,(and here's my question)I did not get from any examples to how should I bind the datasource to the labels and how to pass the parameter(UserId) from runtime and how to call the report from a webform. For example, I have a table called "User" with 3 fields: UserId, Username and Password. In the report designer I place 3 labels. Then I have a webform where the user is entering the userID and pulling some data and I have a print button on that webform when the user clicks the print button the data should be displayed on the report of UserId..

    Read the article

  • WPF ContextMenu with bound items: Items.Count == 0 in ContextMenuOpening event

    - by OregonGhost
    I have a ContextMenu with the ItemsSource bound to the selected item of a list view, like this: <ContextMenu ItemsSource="{Binding Path=PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}, Converter={StaticResource possibleConverter}}"/> The possibleConverter enumerates all possible values for a property of the the selected item, which are shown in the context menu. In the Opened event of the context menu, I select the current value like this: var cm = e.OriginalSource as ContextMenu; if (cm != null) { var lv = cm.PlacementTarget as ListView; var field = lv.SelectedItem as Field; var item = cm.ItemContainerGenerator.ContainerFromItem(cm.Items.OfType<object>().Where(o => o.ToString().Equals(field.StringValue)).FirstOrDefault()) as MenuItem; if (item != null) { item.IsChecked = true; } } Not particularly elegant, but it works. With the debugger I verified that the ContextMenu.Items.Count property has a non-zero value when expected (i.e. cm.Items.Count is non-zero in the if). So far, so good. There are, however, items in the listview where the context menu will have no items. In this case, an empty menu is shown. I tried to suppress this in the ContextMenuOpening event in the list view, like this: var lv = sender as ListView; if (lv != null) { var cm = lv.ContextMenu; if ((cm != null) && (cm.Items.Count > 0)) { // Here we want to check the current item, which is currently done in the Opened event. } else { e.Handled = true; } } Seems like it should work. However, cm.Items.Count is always zero. This is true even if ListView.SelectedItem did not change: For an item with menu entries, the menu is shown correctly after the first click, so the data binding has already happend. It is shown correct the second time as well, but in any case, Items.Count is zero in the ContextMenuOpening event. What am I missing? How can I suppress empty context menus? Why is the count zero in the ContextMenuOpening handler, which is in Windows Forms (ContextMenuStrip.Opening) the canonical point where to do these things? EDIT: Upon further investigating, it turns out that in the ContextMenuOpening handler, any binding to the listview fails, which is why ItemsSource is null. I tried to bind via ElementName, via a FindAncestor relationship, all to no avail. The PlacementTarget is null during that event. An ugly hack worked though: In the ContextMenuOpening event, I assign the list view to the ContextMenu.Tag property, while the ItemsSource binding now binds to Tag.SelectedItem. This updates the binding, so Items.Count is what it should be. It's still strange. How can you do meaningful things in ContextMenuOpening other than replacing the menu or something, if the binding fails because somehow the context menu is out of context during the event? Was it only tested with static pre-defined menu items?

    Read the article

  • Need additional help with binding multiple CommandParameters using MultiBinding

    - by Dave
    I need to have a command handler for a ToggleButton that can take multiple parameters, namely the IsChecked property of said ToggleButton, along with a constant value, which could be a string, byte, int... doesn't matter. I found this great question on SO and followed the answer's link and read up on MultiBinding and IMultiValueConverter. It went really smoothly until I had to write the MultiBinding, when I realized that I also need to pass a constant value and couldn't do something like <Binding Value="1" /> I then came across another similar question that Kent Boogaart answered, and then I started to think about ways that I could get around this. One possible way is to not use MVVM and simply add the Tag property to my ToggleButton, in which case my MultiBinding would look like this: <MultiBinding Converter="{StaticResource MyConverter}"> <MultiBinding.Bindings> <Binding Path="IsChecked" /> <Binding Path="Tag" /> </MultiBinding.Bindings> </MultiBinding> Kent had made a comment along the lines of, "if you're using MVVM you should be able to get around this issue". However, I'm not sure that's an option for me, even though I have adopted MVVM as my WPF pattern of necessity choice. The reason why I say this is that I have wayyyy more than one ToggleButton in the UserControl, and each of the ToggleButtons' Commands need to call the same function. But since they are ToggleButtons, I can't use the property bound to IsChecked in the ViewModel, because I don't know which one was last clicked. I suppose I could add another private property to keep track of this, but it seems a little silly. As far as the constant goes, I could probably get rid of this if I did the tracking idea, but not sure of any other way to get around it. Does anyone have good suggestions for me here? :) EDIT -- ok, so I need to update my bindings, which still don't work quite right: <ToggleButton Tag="1" Command="{Binding MyCommand}" Style="{StaticResource PassFailToggleButtonStyle}" HorizontalContentAlignment="Center" Background="Transparent" BorderBrush="Transparent" BorderThickness="0"> <ToggleButton.CommandParameter> <MultiBinding Converter="{StaticResource MyConverter}"> <MultiBinding.Bindings> <Binding Path="IsChecked" RelativeSource="{RelativeSource Mode=Self}" /> <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}" /> </MultiBinding.Bindings> </MultiBinding> </ToggleButton.CommandParameter> </ToggleButton> IsChecked was working, but not Tag. I just realized that Tag is a string... duh. It's working now! The key was to use a RelativeSource of Self.

    Read the article

  • ListBox SelectedItems Binding

    - by Polaris
    I want to bind Listbox selectedItems to array. But .NET throw exceprion in runtime. d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray }); Where "d" some ListBox from XAML. Exception: Selected Item cannot be bound. Why?

    Read the article

  • Setting a Visual State from a data bound enum in WPF

    - by firoso
    Hey all, I've got a scenario where I want to switch the visiblity of 4 different content controls. The visual states I have set opacity, and collapsed based on each given state (See code.) What I'd like to do is have the visual state bound to a property of my View Model of type Enum. I tried using DataStateBehavior, but it requires true/false, which doesn't work for me. So I tried DataStateSwitchBehavior, which seems to be totally broken for WPF4 from what I could tell. Is there a better way to be doing this? I'm really open to different approaches if need be, but I'd really like to keep this enum in the equation. Edit: The code shouldn't be too important, I just need to know if there's a well known solution to this problem. <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:Custom="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" xmlns:ee="http://schemas.microsoft.com/expression/2010/effects" xmlns:customBehaviors="clr-namespace:SEL.MfgTestDev.ESS.Behaviors" x:Class="SEL.MfgTestDev.ESS.View.PresenterControl" mc:Ignorable="d" d:DesignHeight="624" d:DesignWidth="1104" d:DataContext="{Binding ApplicationViewModel, Mode=OneWay, Source={StaticResource Locator}}"> <Grid> <Grid.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Layout/TerminalViewTemplate.xaml"/> <ResourceDictionary Source="Layout/DebugViewTemplate.xaml"/> <ResourceDictionary Source="Layout/ProgressViewTemplate.xaml"/> <ResourceDictionary Source="Layout/LoadoutViewTemplate.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Grid.Resources> <Custom:Interaction.Behaviors> <customBehaviors:DataStateSwitchBehavior Binding="{Binding ApplicationViewState}"> <customBehaviors:DataStateSwitchCase State="LoadoutState" Value="Loadout"/> </customBehaviors:DataStateSwitchBehavior> </Custom:Interaction.Behaviors> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ApplicationStates" ei:ExtendedVisualStateManager.UseFluidLayout="True"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0:0:1"> <VisualTransition.GeneratedEasingFunction> <SineEase EasingMode="EaseInOut"/> </VisualTransition.GeneratedEasingFunction> <ei:ExtendedVisualStateManager.TransitionEffect> <ee:SmoothSwirlGridTransitionEffect/> </ei:ExtendedVisualStateManager.TransitionEffect> </VisualTransition> </VisualStateGroup.Transitions> <VisualState x:Name="LoadoutState"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LoadoutPage"> <EasingDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="LoadoutPage"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="ProgressState"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="ProgressPage"> <EasingDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="ProgressPage"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="DebugState"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="DebugPage"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="DebugPage"> <EasingDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="TerminalState"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="TerminalPage"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="TerminalPage"> <EasingDoubleKeyFrame KeyTime="0" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <ContentControl x:Name="LoadoutPage" ContentTemplate="{StaticResource LoadoutViewTemplate}" Opacity="0" Content="{Binding}" Visibility="Collapsed"/> <ContentControl x:Name="ProgressPage" ContentTemplate="{StaticResource ProgressViewTemplate}" Opacity="0" Content="{Binding}" Visibility="Collapsed"/> <ContentControl x:Name="DebugPage" ContentTemplate="{StaticResource DebugViewTemplate}" Opacity="0" Content="{Binding}" Visibility="Collapsed"/> <ContentControl x:Name="TerminalPage" ContentTemplate="{StaticResource TerminalViewTemplate}" Opacity="0" Content="{Binding}" Visibility="Collapsed"/> <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding ApplicationViewState}"> <TextBlock.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="White" Offset="1"/> </LinearGradientBrush> </TextBlock.Background> </TextBlock> </Grid>

    Read the article

  • C# WPF XAML DataTable binding to relation

    - by LnDCobra
    I have 2 tables: COmpany {CompanyID, CompanyName} Deal {CompanyID, Value} And I have a listbox: <ListBox Name="Deals" Height="100" Width="420" Margin="0,20,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Visible" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" SelectionChanged="Deals_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding companyRowByBuyFromCompanyFK.CompanyName}" FontWeight="Bold" /> <TextBlock Text=" -> TGS -> " /> <TextBlock Text="{Binding BuyFrom}" FontWeight="Bold" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> As you can see, I want to display the CompanyName rather then the ID which is a foreign Key. The relation "companyRowByBuyFromCompanyFK" exists, as in Deals_SelectionChanged I can access companyRowByBuyFromCompanyFK property of the Deals row, and I also can access the CompanyName propert of that row. Is the reason why this is not working because XAML binding uses the [] indexer? Rather than properties on the CompanyRows in my DataTable? At the moment im getting values such as - TGS - 3 - TGS - 4 Any ideas? Edit: I still can't get this to work, What would be the best way to accomplish this? Make a converter to convert foreign keys using Table being referenced as custom parameter. Create Table View for each table? This would be long winded as I have quite a large number of tables that have foreign keys.

    Read the article

  • How can I make a WPF TreeView data binding lazy and asynchronous?

    - by pauldoo
    I am learning how to use data binding in WPF for a TreeView. I am procedurally creating the Binding object, setting Source, Path, and Converter properties to point to my own classes. I can even go as far as setting IsAsync and I can see the GUI update asynchronously when I explore the tree. So far so good! My problem is that WPF eagerly evaluates parts of the tree prior to them being expanded in the GUI. If left long enough this would result in the entire tree being evaluated (well actually in this example my tree is infinite, but you get the idea). I would like the tree only be evaluated on demand as the user expands the nodes. Is this possible using the existing asynchronous data binding stuff in the WPF? As an aside I have not figured out how ObjectDataProvider relates to this task. My XAML code contains only a single TreeView object, and my C# code is: public partial class Window1 : Window { public Window1() { InitializeComponent(); treeView.Items.Add( CreateItem(2) ); } static TreeViewItem CreateItem(int number) { TreeViewItem item = new TreeViewItem(); item.Header = number; Binding b = new Binding(); b.Converter = new MyConverter(); b.Source = new MyDataProvider(number); b.Path = new PropertyPath("Value"); b.IsAsync = true; item.SetBinding(TreeView.ItemsSourceProperty, b); return item; } class MyDataProvider { readonly int m_value; public MyDataProvider(int value) { m_value = value; } public int[] Value { get { // Sleep to mimick a costly operation that should not hang the UI System.Threading.Thread.Sleep(2000); System.Diagnostics.Debug.Write(string.Format("Evaluated for {0}\n", m_value)); return new int[] { m_value * 2, m_value + 1, }; } } } class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // Convert the double to an int. int[] values = (int[])value; IList<TreeViewItem> result = new List<TreeViewItem>(); foreach (int i in values) { result.Add(CreateItem(i)); } return result; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new InvalidOperationException("Not implemented."); } } } Note: I have previously managed to do lazy evaluation of the tree nodes by adding WPF event handlers and directly adding items when the event handlers are triggered. I'm trying to move away from that and use data binding instead (which I understand is more in spirit with "the WPF way").

    Read the article

  • WPF DataGrid and Avalon TimePicker binding problem

    - by Jorge Vargas
    I'm using a the WPF DataGrid from the wpf toolkit and a TimePicker from AvalonControlsLibrary to insert a collection of TimeSpans. My problem is that bindings are not working inside the DataGrid, and I have no clue of why this isn't working. Here is my setup: I have the following XAML: <Window x:Class="Views.TestMainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpf="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:a="http://schemas.AvalonControls/AvalonControlsLibrary/Controls" SizeToContent="WidthAndHeight" MinHeight="250" MinWidth="300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <GroupBox Grid.Row="0"> <GroupBox.Header> Testing it: </GroupBox.Header> <wpf:DataGrid ItemsSource="{Binding Path=TestSpans}" AutoGenerateColumns="False"> <wpf:DataGrid.Columns> <wpf:DataGridTemplateColumn Header="Start"> <wpf:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <a:TimePicker SelectedTime="{Binding Path=., Mode=TwoWay}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellEditingTemplate> <wpf:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellTemplate> </wpf:DataGridTemplateColumn> </wpf:DataGrid.Columns> </wpf:DataGrid> </GroupBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Row="1"> <a:TimePicker SelectedTime="{Binding Path=SelectedTime, Mode=TwoWay}" /> </StackPanel> </Grid> And this is my ViewModel: Imports System.Collections.ObjectModel Namespace ViewModels Public Class TestMainWindowViewModel Private _selectedTime As TimeSpan = DateTime.Now.TimeOfDay Public Property SelectedTime() As TimeSpan Get Return _selectedTime End Get Set(ByVal value As TimeSpan) _selectedTime = value End Set End Property Private _testSpans As ObservableCollection(Of TimeSpan) = New ObservableCollection(Of TimeSpan) Public Property TestSpans() As ObservableCollection(Of TimeSpan) Get Return _testSpans End Get Set(ByVal value As ObservableCollection(Of TimeSpan)) _testSpans = value End Set End Property Public Sub New() _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) End Sub End Class End Namespace I'm starting this window in application.xaml.vb like this: Class Application ' Application-level events, such as Startup, Exit, and DispatcherUnhandledException ' can be handled in this file. Protected Overrides Sub OnStartup(ByVal e As System.Windows.StartupEventArgs) MyBase.OnStartup(e) Dim window As Views.TestMainWindow = New Views.TestMainWindow window.DataContext = New TestMainWindowViewModel() window.Show() End Sub End Class

    Read the article

  • WPF RelativeSource FindAncestor doesn't work outside of the Control.Resources context?

    - by sker
    I have this VisualBrush resource I took from some site and I apply it with triggers to a TextBox. <VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.4" Stretch="None" AlignmentX="Left"> <VisualBrush.Visual> <TextBlock FontStyle="Italic" Text="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType={x:Type Control}, AncestorLevel=1}}"/> </VisualBrush.Visual> </VisualBrush> <Style x:Key="DefaultText" TargetType="TextBox"> <Style.Triggers> <Trigger Property="Text" Value="{x:Null}"> <Setter Property="Background" Value="{StaticResource HelpBrush}"/> </Trigger> <Trigger Property="Text" Value=""> <Setter Property="Background" Value="{StaticResource HelpBrush}"/> </Trigger> </Style.Triggers> </Style> If I place both the VisualBrush and the Style inside the TextBox.Resources tag in XAML, it works fine. But if I take it out and place it in the Window.Resources or a merged dictionary, it stops working. The problem is the Binding, it doesn't find the ancestor TextBox for some reason. I already tried removing AncestorLevel and using AncestorType={x:Type TextBox} - it doesn't work. Any ideas?

    Read the article

  • Nested property binding

    - by EtherealMonkey
    Recently, I have been trying to wrap my mind around the BindingList<T> and INotifyPropertChanged. More specifically - How do I make a collection of objects (having objects as properties) which will allow me to subscribe to events throughout the tree? To that end, I have examined the code offered as examples by others. One such project that I downloaded was Nested Property Binding - CodeProject by "seesharper". Now, the article explains the implementation, but there was a question by "Someone@AnotherWorld" about "INotifyPropertyChanged in nested objects". His question was: Hi, nice stuff! But after a couple of time using your solution I realize the ObjectBindingSource ignores the PropertyChanged event of nested objects. E.g. I've got a class 'Foo' with two properties named 'Name' and 'Bar'. 'Name' is a string an 'Bar' reference an instance of class 'Bar', which has a 'Name' property of type string too and both classes implements INotifyPropertyChanged. With your binding source reading and writing with both properties ('Name' and 'Bar_Name') works fine but the PropertyChanged event works only for the 'Name' property, because the binding source listen only for events of 'Foo'. One workaround is to retrigger the PropertyChanged event in the appropriate class (here 'Foo'). What's very unclean! The other approach would be to extend ObjectBindingSource so that all owner of nested property which implements INotifyPropertyChanged get used for receive changes, but how? Thanks! I had asked about BindingList<T> yesterday and received a good answer from Aaronaught. In my question, I had a similar point as "Someone@AnotherWorld": if Keywords were to implement INotifyPropertyChanged, would changes be accessible to the BindingList through the ScannedImage object? To which Aaronaught's response was: No, they will not. BindingList only looks at the specific object in the list, it has no ability to scan all dependencies and monitor everything in the graph (nor would that always be a good idea, if it were possible). I understand Aaronaught's comment regarding this behavior not necessarily being a good idea. Additionally, his suggestion to have my bound object "relay" events on behalf of it's member objects works fine and is perfectly acceptable. For me, "re-triggering" the PropertyChanged event does not seem so unclean as "Someone@AnotherWorld" laments. I do understand why he protests - in the interest of loosely coupled objects. However, I believe that coupling between objects that are part of a composition is logical and not so undesirable as this may be in other scenarios. (I am a newb, so I could be waaayyy off base.) Anyway, in the interest of exploring an answer to the question by "Someone@AnotherWorld", I altered the MainForm.cs file of the example project from Nested Property Binding - CodeProject by "seesharper" to the following: using System; using System.Collections.Generic; using System.ComponentModel; using System.Core.ComponentModel; using System.Windows.Forms; namespace ObjectBindingSourceDemo { public partial class MainForm : Form { private readonly List<Customer> _customers = new List<Customer>(); private readonly List<Product> _products = new List<Product>(); private List<Order> orders; public MainForm() { InitializeComponent(); dataGridView1.AutoGenerateColumns = false; dataGridView2.AutoGenerateColumns = false; CreateData(); } private void CreateData() { _customers.Add( new Customer(1, "Jane Wilson", new Address("98104", "6657 Sand Pointe Lane", "Seattle", "USA"))); _customers.Add( new Customer(1, "Bill Smith", new Address("94109", "5725 Glaze Drive", "San Francisco", "USA"))); _customers.Add( new Customer(1, "Samantha Brown", null)); _products.Add(new Product(1, "Keyboard", 49.99)); _products.Add(new Product(2, "Mouse", 10.99)); _products.Add(new Product(3, "PC", 599.99)); _products.Add(new Product(4, "Monitor", 299.99)); _products.Add(new Product(5, "LapTop", 799.99)); _products.Add(new Product(6, "Harddisc", 89.99)); customerBindingSource.DataSource = _customers; productBindingSource.DataSource = _products; orders = new List<Order>(); orders.Add(new Order(1, DateTime.Now, _customers[0])); orders.Add(new Order(2, DateTime.Now, _customers[1])); orders.Add(new Order(3, DateTime.Now, _customers[2])); #region Added by me OrderLine orderLine1 = new OrderLine(_products[0], 1); OrderLine orderLine2 = new OrderLine(_products[1], 3); orderLine1.PropertyChanged += new PropertyChangedEventHandler(OrderLineChanged); orderLine2.PropertyChanged += new PropertyChangedEventHandler(OrderLineChanged); orders[0].OrderLines.Add(orderLine1); orders[0].OrderLines.Add(orderLine2); #endregion // Removed by me in lieu of region above. //orders[0].OrderLines.Add(new OrderLine(_products[0], 1)); //orders[0].OrderLines.Add(new OrderLine(_products[1], 3)); ordersBindingSource.DataSource = orders; } #region Added by me // Have to wait until the form is Shown to wire up the events // for orderDetailsBindingSource. Otherwise, they are triggered // during MainForm().InitializeComponent(). private void MainForm_Shown(object sender, EventArgs e) { orderDetailsBindingSource.AddingNew += new AddingNewEventHandler(orderDetailsBindSrc_AddingNew); orderDetailsBindingSource.CurrentItemChanged += new EventHandler(orderDetailsBindSrc_CurrentItemChanged); orderDetailsBindingSource.ListChanged += new ListChangedEventHandler(orderDetailsBindSrc_ListChanged); } private void orderDetailsBindSrc_AddingNew( object sender, AddingNewEventArgs e) { } private void orderDetailsBindSrc_CurrentItemChanged( object sender, EventArgs e) { } private void orderDetailsBindSrc_ListChanged( object sender, ListChangedEventArgs e) { ObjectBindingSource bindingSource = (ObjectBindingSource)sender; if (!(bindingSource.Current == null)) { // Unsure if GetType().ToString() is required b/c ToString() // *seems* // to return the same value. if (bindingSource.Current.GetType().ToString() == "ObjectBindingSourceDemo.OrderLine") { if (e.ListChangedType == ListChangedType.ItemAdded) { // I wish that I knew of a way to determine // if the 'PropertyChanged' delegate assignment is null. // I don't like the current test, but it seems to work. if (orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].Product == null) { orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].PropertyChanged += new PropertyChangedEventHandler( OrderLineChanged); } } if (e.ListChangedType == ListChangedType.ItemDeleted) { // Will throw exception when leaving // an OrderLine row with unitialized properties. // // I presume this is because the item // has already been 'disposed' of at this point. // *but* // Will it be actually be released from memory // if the delegate assignment for PropertyChanged // was never removed??? if (orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].Product != null) { orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].PropertyChanged -= new PropertyChangedEventHandler( OrderLineChanged); } } } } } private void OrderLineChanged(object sender, PropertyChangedEventArgs e) { MessageBox.Show(e.PropertyName, "Property Changed:"); } #endregion } } In the method private void orderDetailsBindSrc_ListChanged(object sender, ListChangedEventArgs e) I am able to hook up the PropertyChangedEventHandler to the OrderLine object as it is being created. However, I cannot seem to find a way to unhook the PropertyChangedEventHandler from the OrderLine object before it is being removed from the orders[i].OrderLines list. So, my questions are: Am I simply trying to do something that is very, very wrong here? Will the OrderLines object that I add the delegate assignments to ever be released from memory if the assignment is not removed? Is there a "sane" method of achieving this scenario? Also, note that this question is not specifically related to my prior. I have actually solved the issue which had prompted me to inquire before. However, I have reached a point with this particular topic of discovery where my curiosity has exceeded my patience - hopefully someone here can shed some light on this?

    Read the article

  • Winforms BindingSource

    - by Erez
    I have a binding source object that fills some textboxes. In run time, after editing the textboxes I want to be able to retrieve the old values. how can I retrieve the Textbox's old value and refresh the screen ? Maybe the binding source has history or something ?!

    Read the article

  • Binding to a dictionary in Silverlight with INotifyPropertyChanged

    - by rip
    In silverlight, I can not get INotifyPropertyChanged to work like I want it to when binding to a dictionary. In the example below, the page binds to the dictionary okay but when I change the content of one of the textboxes the CustomProperties property setter is not called. The CustomProperties property setter is only called when CustomProperties is set and not when the values within it are set. I am trying to do some validation on the dictionary values and so am looking to run some code when each value within the dictionary is changed. Is there anything I can do here? C# public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); MyEntity ent = new MyEntity(); ent.CustomProperties.Add("Title", "Mr"); ent.CustomProperties.Add("FirstName", "John"); ent.CustomProperties.Add("Name", "Smith"); this.DataContext = ent; } } public class MyEntity : INotifyPropertyChanged { public event PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged; public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e); private Dictionary<string, object> _customProps; public Dictionary<string, object> CustomProperties { get { if (_customProps == null) { _customProps = new Dictionary<string, object>(); } return _customProps; } set { _customProps = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("CustomProperties")); } } } } VB Partial Public Class MainPage Inherits UserControl Public Sub New() InitializeComponent() Dim ent As New MyEntity ent.CustomProperties.Add("Title", "Mr") ent.CustomProperties.Add("FirstName", "John") ent.CustomProperties.Add("Name", "Smith") Me.DataContext = ent End Sub End Class Public Class MyEntity Implements INotifyPropertyChanged Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged Private _customProps As Dictionary(Of String, Object) Public Property CustomProperties As Dictionary(Of String, Object) Get If _customProps Is Nothing Then _customProps = New Dictionary(Of String, Object) End If Return _customProps End Get Set(ByVal value As Dictionary(Of String, Object)) _customProps = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CustomProperties")) End Set End Property End Class Xaml <TextBox Height="23" Name="TextBox1" Text="{Binding Path=CustomProperties[Title], Mode=TwoWay}" /> <TextBox Height="23" Name="TextBox2" Text="{Binding Path=CustomProperties[FirstName], Mode=TwoWay}" /> <TextBox Height="23" Name="TextBox3" Text="{Binding Path=CustomProperties[Name], Mode=TwoWay}" />

    Read the article

  • MVC map to nullable bool in model

    - by fearofawhackplanet
    With a view model containing the field: public bool? IsDefault { get; set; } I get an error when trying to map in the view: <%= Html.CheckBoxFor(model => model.IsDefault) %> Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) I've tried casting, and using .Value and neither worked. Note the behaviour I would like is that submitting the form should set IsDefault in the model to true or false. A value of null simply means that the model has not been populated.

    Read the article

  • Binding Dictionary<T> to a WPF ListBox

    - by Joan Venge
    Given a dictionary of <string, Drink>, how would you bind the dictionary.Values to a WPF ListBox, so that the items use the .Name property? struct Drink { public string Name { get; private set; } public int Popularity { get; private set; } public Drink ( string name, int popularity ) : this ( ) { this.Name = name; this.Popularity = popularity; } }

    Read the article

  • Binding to an ObservableCollection attached property.

    - by bwreichle
    I want to create an attached property of type ObservableCollection<Notification> and bind it to a property of the same type on the DataContext. Currently I have: internal static class Squiggle { public static readonly DependencyProperty NotificationsProperty = DependencyProperty.RegisterAttached( "Notifications", typeof(ObservableCollection<Notification>), typeof(TextBox), new FrameworkPropertyMetadata(null, NotificationsPropertyChanged, CoerceNotificationsPropertyValue)); public static void SetNotifications(TextBox textBox, ObservableCollection<Notification> value) { textBox.SetValue(NotificationsProperty, value); } public static ObservableCollection<Notification> GetNotifications(TextBox textBox) { return (ObservableCollection<Notification>)textBox.GetValue(NotificationsProperty); } ... } With the following XAML: <TextBox x:Name="configTextBox" Text="{Binding Path=ConfigText, UpdateSourceTrigger=PropertyChanged}" AcceptsReturn="True" AcceptsTab="True" local:Squiggle.Notifications="{Binding Path=Notifications}" /> Unfortunatly, when I actually run this I get an exception stating: A 'Binding' cannot be used within a 'TextBox' collection. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. This only seems to be a problem when the attached property is of type ObservableCollection so it seems like WPF is trying to do something magical when binding properties of this type and getting confused in the process. Anyone know what I need to do to make it work?

    Read the article

  • WPF Binding Failure performance hit vs Exception

    - by Aran Mulholland
    when we bind to heterogeneous collection of objects, not all objects have the same set of properties. in the output window we get a message like: System.Windows.Data Error: 39 : BindingExpression path error: 'RoundingFactor' property not found on 'object' ''MultiLineTextMarkingScheme' (HashCode=7262386)'. BindingExpression:Path=RoundingFactor;.......... This doesn't appear to be an exception, but we are concerned it has a performance impact. Should we be concerned and create a view model that has all the properties we wish to bind to (and have the properties that dont exist on the underlying element return null) or can we just leave it. This situation often occurs in a grid scenario where there might be large numbers of these binding failures.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >