Search Results

Search found 63 results on 3 pages for 'ivalueconverter'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Wpf binding to a function

    - by carlopenid
    I've a created a simple scrollviewer (pnlDayScroller) and want to have a separate horizontal scrollbar (associated scroller) to do the horizontal scrolling. All works with the below code accept I need to bind the visibility of the associated scroller. I can't simply bind this to the visibility property of the horizontal template part of the scroll viewer as I've set this to be always hidden. The only way I can think to do this is to bind the visibility of the associated scroller to a function such that If associatedScroller.scrollableWidth > 0 then associatedScroller.visibility = visibility.visible else associatedScroller.visibility = visibility.collapsed end if Is this possible to do and if so how do I do it? Private Sub pnlDayScroller_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles pnlDayScroller.Loaded Dim binViewport, binMax, binMin, binSChange, binLChange As Binding Dim horizontalScrollBar As Primitives.ScrollBar = CType(pnlDayScroller.Template.FindName("PART_HorizontalScrollBar", pnlDayScroller), Primitives.ScrollBar) binViewport = New Binding("ViewportSize") binViewport.Mode = BindingMode.OneWay binViewport.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.ViewportSizeProperty, binViewport) binMax = New Binding("Maximum") binMax.Mode = BindingMode.OneWay binMax.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.MaximumProperty, binMax) binMin = New Binding("Minimum") binMin.Mode = BindingMode.OneWay binMin.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.MinimumProperty, binMin) binSChange = New Binding("SmallChange") binSChange.Mode = BindingMode.OneWay binSChange.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.SmallChangeProperty, binSChange) binLChange = New Binding("LargeChange") binLChange.Mode = BindingMode.OneWay binLChange.Source = horizontalScrollBar associatedScroller.SetBinding(Primitives.ScrollBar.LargeChangeProperty, binLChange) End Sub Private Sub associatedScroller_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of Double)) Handles associatedScroller.ValueChanged pnlDayScroller.ScrollToHorizontalOffset(e.NewValue) end sub FOLLOW UP (thanks to JustABill) : I've add this code into the pnlDayScroller sub above (I've discovered scrollableWidth is a property of scrollviewer not scrollbar, but the maximum property gives a result I can use instead) binVisibility = New Binding("Maximum") binVisibility.Mode = BindingMode.OneWay binVisibility.Source = horizontalScrollBar binVisibility.Converter = New ScrollableConverter associatedScroller.SetBinding(Primitives.ScrollBar.VisibilityProperty, binVisibility) and I've created this class Public Class ScrollableConverter Implements IValueConverter Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert Dim dblMaximum As Double If targetType IsNot GetType(Visibility) Then Throw New InvalidOperationException("The target must be a visibility") Else dblMaximum = CType(value, Double) Debug.WriteLine("Value of double is " & dblMaximum) If dblMaximum > 0 Then Return Visibility.Visible Else Return Visibility.Collapsed End If End If End Function Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack Throw New NotSupportedException() End Function End Class And the problem is resolved.

    Read the article

  • Show WPF tooltip on disabled item only

    - by DT
    Just wondering if it is possible to show a WPF on a disabled item ONLY (and not when the item is enabled). I would like to give the user a tooltip explaining why an item is currently disabled. I have an IValueConverter to invert the boolean IsEnabled property binding. But it doesn't seem to work in this situation. The tooltip is show both when the item is enabled and disabled. So is is possible to bind a tooltip.IsEnabled property exclusively to an item's own !IsEnabled? Pretty straightforward question I guess, but code example here anyway: public class BoolToOppositeBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } #endregion } And the binding: <TabItem Header="Tab 2" Name="tabItem2" ToolTip="Not enabled in this situation." ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding Path=IsEnabled, ElementName=tabItem2, Converter={StaticResource oppositeConverter}}"> <Label Content="Item content goes here" /> </TabItem> Thanks folks.

    Read the article

  • Non breaking space in XAML vs. code

    - by Henrik Söderlund
    This works fine, and correctly inserts non-breaking spaces into the string: <TextBlock Text="Non&#160;Breaking&#160;Text&#160;Here"></TextBlock> But what I really need is to replace spaces with non-breaking spaces during data binding. So I wrote a simple value converter that replaces spaces with "&#160;". It does indeed replace spaces with "&#160;" but "&#160;" is displayed literally instead of showing as a non-breaking space. This is my converter: public class SpaceToNbspConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString().Replace(" ", "&#160;"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } Does anybody know why it works in XAML, but not in code? /Henrik

    Read the article

  • Silverlight Cream for June 15, 2010 -- #882

    - by Dave Campbell
    In this Issue: Colin Eberhardt Zoltan Arvai, Marcel du Preez, Mark Tucker, John Papa, Phil Middlemiss, Andy Beaulieu, and Chad Campbell. From SilverlightCream.com: Throttling Silverlight Mouse Events to Keep the UI Responsive Colin Eberhardt sent me this link to his latest at Scott Logic... about how to throttle Silverlight -- no not that, you'd have to go to one of the *other* blogs for that :) ... this is throttling the mouse, particularly the mouse wheel to keep the UI from freezing up ... check out the demos, you'll want to read the code Data Driven Applications with MVVM Part I: The Basics Zoltan Arvai started a series of tutorials on Data-Driven Applications with MVVM at SilverlightShow... this is number 1, and it looks like it's going to be a good series to read. Red-To-Green scale using an IValueConverter Marcel du Preez has an interesting post up at SilverlightShow using an IValueConverter to do a red/yellow/green progress bar ... this is pretty cool. Infragistics XamWebOutlookBar & Caliburn With assistance from Rob Eisenburg, Mark Tucker was able to build a Caliburn sample including the Infragistics XamWebOutlookBar, and he's sharing his experience (and code) with all of us. Printing Tip – Handling User Initiated Dialogs Exceptions John Papa responded to a common printing problem by writing it up in his blog. Note this problem quite often appears during debug, so check it out... John also has a quick tip on an update to the PrintAPI in Silverlight 4. Automatic Rectangle Radius X and Y Phil Middlemiss has another great Blend post up -- this one on rounding off buttons... they look great to me, but he's looking for advice -- how about that Phil? They look great to me :) WP7 Back Button in Games Planning on selling 'stuff' in the Windows Phone Marketplace? Are you familiar with the required use of the Back Button? How about in a game? ... Andy Beaulieu discusses all this and has some code you'll want to use. Windows Phone 7 – Call Phone Number from HyperlinkButton Chad Campbell [no relation :) ] is discussing dialing a number from a hyperlink in WP7 - oh yeah, it's a phone as well :) -- I think I've only seen a number attempt to be called -- hmm... and we're not yet either because we all have emulators, but this is a good intro to the functionality for when we may actually have devices! Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Text Trimming in Silverlight 4

    - by dwahlin
    Silverlight 4 has a lot of great features that can be used to build consumer and Line of Business (LOB) applications. Although Webcam support, RichTextBox, MEF, WebBrowser and other new features are pretty exciting, I’m actually enjoying some of the more simple features that have been added such as text trimming, built-in wheel scrolling with ScrollViewer and data binding enhancements such as StringFormat. In this post I’ll give a quick introduction to a simple yet productive feature called text trimming and show how it eliminates a lot of code compared to Silverlight 3. The TextBlock control contains a new property in Silverlight 4 called TextTrimming that can be used to add an ellipsis (…) to text that doesn’t fit into a specific area on the user interface. Before the TextTrimming property was available I used a value converter to trim text which meant passing in a specific number of characters that I wanted to show by using a parameter: public class StringTruncateConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int maxLength; if (int.TryParse(parameter.ToString(), out maxLength)) { string val = (value == null) ? null : value.ToString(); if (val != null && val.Length > maxLength) { return val.Substring(0, maxLength) + ".."; } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } To use the StringTruncateConverter I'd define the standard xmlns prefix that referenced the namespace and assembly, add the class into the application’s Resources section and then use the class while data binding as shown next: <TextBlock Grid.Column="1" Grid.Row="3" ToolTipService.ToolTip="{Binding ReportSummary.ProjectManagers}" Text="{Binding ReportSummary.ProjectManagers, Converter={StaticResource StringTruncateConverter},ConverterParameter=16}" Style="{StaticResource SummaryValueStyle}" /> With Silverlight 4 I can define the TextTrimming property directly in XAML or use the new Property window in Visual Studio 2010 to set it to a value of WordEllipsis (the default value is None): <TextBlock Grid.Column="1" Grid.Row="4" ToolTipService.ToolTip="{Binding ReportSummary.ProjectCoordinators}" Text="{Binding ReportSummary.ProjectCoordinators}" TextTrimming="WordEllipsis" Style="{StaticResource SummaryValueStyle}"/> The end result is a nice trimming of the text that doesn’t fit into the target area as shown with the Coordinator and Foremen sections below. My data binding statements are now much smaller and I can eliminate the StringTruncateConverter class completely.   For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

    Read the article

  • A Generic Boolean Value Converter

    - by codingbloke
    On fairly regular intervals a question on Stackoverflow like this one:  Silverlight Bind to inverse of boolean property value appears.  The same answers also regularly appear.  They all involve an implementation of IValueConverter and basically include the same boilerplate code. The required output type sometimes varies, other examples that have passed by are Boolean to Brush and Boolean to String conversions.  Yet the code remains pretty much the same.  There is therefore a good case to create a generic Boolean to value converter to contain this common code and then just specialise it for use in Xaml. Here is the basic converter:- BoolToValueConverter using System; using System.Windows.Data; namespace SilverlightApplication1 {     public class BoolToValueConverter<T> : IValueConverter     {         public T FalseValue { get; set; }         public T TrueValue { get; set; }         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             if (value == null)                 return FalseValue;             else                 return (bool)value ? TrueValue : FalseValue;         }         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             return value.Equals(TrueValue);         }     } } With this generic converter in place it easy to create a set of converters for various types.  For example here are all the converters mentioned so far:- Value Converters using System; using System.Windows; using System.Windows.Media; namespace SilverlightApplication1 {     public class BoolToStringConverter : BoolToValueConverter<String> { }     public class BoolToBrushConverter : BoolToValueConverter<Brush> { }     public class BoolToVisibilityConverter : BoolToValueConverter<Visibility> { }     public class BoolToObjectConverter : BoolToValueConverter<Object> { } } With the specialised converters created they can be specified in a Resources property on a user control like this:- <local:BoolToBrushConverter x:Key="Highlighter" FalseValue="Transparent" TrueValue="Yellow" /> <local:BoolToStringConverter x:Key="CYesNo" FalseValue="No" TrueValue="Yes" /> <local:BoolToVisibilityConverter x:Key="InverseVisibility" TrueValue="Collapsed" FalseValue="Visible" />

    Read the article

  • Silverlight Cream for March 21, 2010 -- #816

    - by Dave Campbell
    In this Issue: Michael Washington, John Papa(-2-, -3-, -4-), Jonas Follesø, David Anson, Scott Guthrie, Andrej Tozon, Bill Reiss(-2-), Pete Blois, and Lee. Shoutouts: Frank LaVigne has a Mix10 Session Downloader for us all to use... thanks Frank! Read what Ward Bell has to say about MVVM, Josh Smith’s Way ... it's all good. Robby Ingebretsen posts on his 10 Favorite Open Source Fonts You Can Embed in WPF or Silverlight Mike Harsh posted Slides and Demos from my MIX10 Session . The download link at Drop.io is down for maintenance until Sunday evening, March 21. From SilverlightCream.com: Blend 4: TreeView SelectedItemChanged using MVVM Michael Washington has a post up about doing SelectedItemChanged on a TreeView with MVVM, oh and he's starting out in Blend 4... Silverlight TV 14: Developing for Windows Phone 7 with Silverlight John Papa hit Silverlight TV pretty hard at the beginning of MIX10. This first one is with Mike Harsh talking about WP7. (Hi Mike ... wondered where you'd run off to!), and you can go to the shoutout section to get Mike's session material from MIX as well. Silverlight TV 15: Announcing Silverlight 4 RC at MIX 10 In this next Silverlight TV(15), John Papa and Adam Kinney discuss Silverlight 4RC ... thank goodness it's out, we can all let go of the breath we've been holding in :) Silverlight TV 16: Tim Heuer and Jesse Liberty Talk about Silverlight 4 RC at MIX 10 Silverlight TV 16 has John Papa sharing the spotlight with Jesse Liberty and Tim Heuer ... geez... can you find 3 more kowledgable Silverlight folks to listen to? No? then go listen to this :) Silverlight TV 17: Build a Twitter Client for Windows Phone 7 with Silverlight The latest Silverlight TV has John Papa bringing Mike Harsh back to produce a Twitter Client for WP7. Simulating multitouch on the Windows Phone 7 Emulator Jonas Follesø has a great post up about simulating multi-touch on WP7 using multiple mice ... yeah, you read that right :) Using IValueConverter to create a grouped list of items simply and flexibly David Anson demonstrates grouping items in a ListBox using IValueConverter. I think I can pretty well guarantee I would NOT have thought of doing this.. :) Building a Windows Phone 7 Twitter Application using Silverlight In the MIX10 first-day keynote, Scott Guthrie did File->New Project and built a WP7 Twitter app. He has that up as a tutorial with all sorts of external links including one to the keynote itself. Named and optional parameters in Silverlight 4 Andrej Tozon delves into the optional parameters that are now available to Silverlight developers... pretty cool stuff. Space Rocks game step 4: Inheriting from Sprite Bill Reiss continues with his game development series with this one on inheriting from the Sprite class and centering objects Space Rocks game step 5: Rotating the ship Bill Reiss's episode 5 is on rotating the ship you setup in episode 4. Don't worry about the transforms, Bill gives it all to us :) Labyrinth Sample for Windows Phone Wow... check out the sample Pete Blois did for the Phone... Silverlight coolness :) PathListBox in SL4 – firstlook Lee has a post up on the PathListBox. I think this is going to catch on quick... it's just too cool not to! Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • WPF designer gives exception when databinding a label to a checkbox

    - by John
    I'm sure it's something stupid, but I'm playing around with databinding. I have a checkbox and a label on a form. What I'm trying to do is simply bind the Content of the label to the checkbox's IsChecked value. What I've done runs fine (no compilation errors and acts as expected), but if I touch the label in the XAML, the designer trows an exception: System.NullReferenceException Object reference not set to an instance of an object. at MS.Internal.Designer.PropertyEditing.Editors.MarkupExtensionInlineEditorControl.BuildBindingString(Boolean modeSupported, PropertyEntry propertyEntry) at <Window x:Class="UnitTestHelper.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:FileSysCtls="clr-namespace:WPFFileSystemUserControls;assembly=WPFFileSystemUserControls" xmlns:HelperClasses="clr-namespace:UnitTestHelper" Title="MainWindow" Height="406" Width="531"> <Window.Resources> <HelperClasses:ThreestateToBinary x:Key="CheckConverter" /> </Window.Resources> <Grid Height="367" Width="509"> <CheckBox Content="Step into subfolders" Height="16" HorizontalAlignment="Left" Margin="17,254,0,0" Name="chkSubfolders" VerticalAlignment="Top" Width="130" IsThreeState="False" /> <Label Height="28" HorizontalAlignment="Left" Margin="376,254,0,0" Name="lblStepResult" VerticalAlignment="Top" Width="120" IsEnabled="True" Content="{Binding IsChecked, ElementName=chkSubfolders, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource CheckConverter}}" /> </Grid> The ThreeStateToBinary class is as follows: class ThreestateToBinary : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if ((bool)value) return "Checked"; else return "Not checked"; //throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((string)value == "Checked"); //throw new NotImplementedException(); } #endregion } Quite honestly, I'm playing around with it at this point. It was originally simpler (not using the ValueConverter) but was displaying similar behavior when I simply had the content set to: Content="{Binding IsChecked, ElementName=chkSubfolders, UpdateSourceTrigger=PropertyChanged}" Any ideas? Thanks, John

    Read the article

  • Binding ComboBoxes to enums... in Silverlight!

    - by Domenic
    So, the web, and StackOverflow, have plenty of nice answers for how to bind a combobox to an enum property in WPF. But Silverlight is missing all of the features that make this possible :(. For example: You can't use a generic EnumDisplayer-style IValueConverter that accepts a type parameter, since Silverlight doesn't support x:Type. You can't use ObjectDataProvider, like in this approach, since it doesn't exist in Silverlight. You can't use a custom markup extension like in the comments on the link from #2, since markup extensions don't exist in Silverlight. You can't do a version of #1 using generics instead of Type properties of the object, since generics aren't supported in XAML (and the hacks to make them work all depend on markup extensions, not supported in Silverlight). Massive fail! As I see it, the only way to make this work is to either Cheat and bind to a string property in my ViewModel, whose setter/getter does the conversion, loading values into the ComboBox using code-behind in the View. Make a custom IValueConverter for every enum I want to bind to. Are there any alternatives that are more generic, i.e. don't involve writing the same code over and over for every enum I want? I suppose I could do solution #2 using a generic class accepting the enum as a type parameter, and then create new classes for every enum I want that are simply class MyEnumConverter : GenericEnumConverter<MyEnum> {} What are your thoughts, guys?

    Read the article

  • WPF: Binding to ObservableCollection in ControlTemplate is not updated

    - by Julian Lettner
    I created a ControlTemplate for my custom control MyControl. MyControl derives from System.Windows.Controls.Control and defines the following property public ObservableCollection<MyControl> Children{ get; protected set; }. To display the nested child controls I am using an ItemsControl (StackPanel) which is surrounded by a GroupBox. If there are no child controls, I want to hide the GroupBox. Everything works fine on application startup: The group box and child controls are shown if the Children property initially contained at least one element. In the other case it is hidden. The problem starts when the user adds a child control to an empty collection. The GroupBox's visibility is still collapsed. The same problem occurs when the last child control is removed from the collection. The GroupBox is still visible. Another symptom is that the HideEmptyEnumerationConverter converter does not get called. Adding/removing child controls to non empty collections works as expected. Whats wrong with the following binding? Obviously it works once but does not get updated, although the collection I am binding to is of type ObservableCollection. <!-- Converter for hiding empty enumerations --> <Common:HideEmptyEnumerationConverter x:Key="hideEmptyEnumerationConverter"/> <!--- ... ---> <ControlTemplate TargetType="{x:Type MyControl}"> <!-- ... other stuff that works ... --> <!-- Child components --> <GroupBox Header="Children" Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Children, Converter={StaticResource hideEmptyEnumerationConverter}}"> <ItemsControl ItemsSource="{TemplateBinding Children}"/> </GroupBox> </ControlTemplate> . [ValueConversion(typeof (IEnumerable), typeof (Visibility))] public class HideEmptyEnumerationConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int itemCount = ((IEnumerable) value).Cast<object>().Count(); return itemCount == 0 ? Visibility.Collapsed : Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } Another, more general question: How do you guys debug bindings? Found this (http://bea.stollnitz.com/blog/?p=52) but still I find it very hard to do. I am glad for any help or suggestion.

    Read the article

  • When will the ValueConverter's Convert method be called in wpf

    - by sudarsanyes
    I have an ObservableCollection bound to a list box and a boolean property bound to a button. I then defined two converters, one that operates on the collection and the other operates on the boolean property. Whenever I modify the boolean property, the converter's Convert method is called, where as the same is not called if I modify the observable collection. What am I missing?? Snippets for your reference, xaml snipet, <Window.Resources> <local:WrapPanelWidthConverter x:Key="WrapPanelWidthConverter" /> <local:StateToColorConverter x:Key="StateToColorConverter" /> </Window.Resources> <StackPanel> <ListBox x:Name="NamesListBox" ItemsSource="{Binding Path=Names}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel x:Name="ItemWrapPanel" Width="500" Background="Gray"> <WrapPanel.RenderTransform> <TranslateTransform x:Name="WrapPanelTranslatation" X="0" /> </WrapPanel.RenderTransform> <WrapPanel.Triggers> <EventTrigger RoutedEvent="WrapPanel.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="WrapPanelTranslatation" Storyboard.TargetProperty="X" To="{Binding Path=Names,Converter={StaticResource WrapPanelWidthConverter}}" From="525" Duration="0:0:2" RepeatBehavior="100" /> </Storyboard> </BeginStoryboard> </EventTrigger> </WrapPanel.Triggers> </WrapPanel> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Label Content="{Binding}" Width="50" Background="LightGray" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Content="{Binding Path=State}" Background="{Binding Path=State, Converter={StaticResource StateToColorConverter}}" Width="100" Height="100" Click="Button_Click" /> </StackPanel> code behind snippet public class WrapPanelWidthConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ObservableCollection<string> aNames = value as ObservableCollection<string>; return -(aNames.Count * 50); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public class StateToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool aState = (bool)value; if (aState) return Brushes.Green; else return Brushes.Red; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }

    Read the article

  • Prevent ListBox from focusing but leave ListBoxItem(s) focusable (wpf)

    - by modosansreves
    Here is what happens: I have a listbox with items. Listbox has focus. Some item (say, 5th) is selected (has a blue background), but has no 'border'. When I press 'Down' key, the focus moves from ListBox to the first ListBoxItem. (What I want is to make 6th item selected, regardless of the 'border') When I navigate using 'Tab', the Listbox never receives the focus again. But when the collection is emptied and filled again, ListBox itself gets focus, pressing 'Down' moves the focus to the item. How to prevent ListBox from gaining focus? P.S. listBox1.SelectedItem is my own class, I don't know how to make ListBoxItem out of it to .Focus() it. EDIT: the code Xaml: <UserControl.Resources> <me:BooleanToVisibilityConverter x:Key="visibilityConverter"/> <me:BooleanToItalicsConverter x:Key="italicsConverter"/> </UserControl.Resources> <ListBox x:Name="lbItems"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <ProgressBar HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Visibility="{Binding Path=ShowProgress, Converter={StaticResource visibilityConverter}}" Maximum="1" Margin="4,0,0,0" Value="{Binding Progress}" /> <TextBlock Text="{Binding Path=VisualName}" FontStyle="{Binding Path=IsFinished, Converter={StaticResource italicsConverter}}" Margin="4" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> <me:OuterItem Name="Regular Folder" IsFinished="True" Exists="True" IsFolder="True"/> <me:OuterItem Name="Regular Item" IsFinished="True" Exists="True"/> <me:OuterItem Name="Yet to be created" IsFinished="False" Exists="False"/> <me:OuterItem Name="Just created" IsFinished="False" Exists="True"/> <me:OuterItem Name="In progress" IsFinished="False" Exists="True" Progress="0.7"/> </ListBox> where OuterItem is: public class OuterItem : IOuterItem { public Guid Id { get; set; } public string Name { get; set; } public bool IsFolder { get; set; } public bool IsFinished { get; set; } public bool Exists { get; set; } public double Progress { get; set; } /// Code below is of lesser importance, but anyway /// #region Visualization helper properties public bool ShowProgress { get { return !IsFinished && Exists; } } public string VisualName { get { return IsFolder ? "[ " + Name + " ]" : Name; } } #endregion public override string ToString() { if (IsFinished) return Name; if (!Exists) return " ??? " + Name; return Progress.ToString("0.000 ") + Name; } public static OuterItem Get(IOuterItem item) { return new OuterItem() { Id = item.Id, Name = item.Name, IsFolder = item.IsFolder, IsFinished = item.IsFinished, Exists = item.Exists, Progress = item.Progress }; } } ?onverters are: /// Are of lesser importance too (for understanding), but will be useful if you copy-paste to get it working public class BooleanToItalicsConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool normal = (bool)value; return normal ? FontStyles.Normal : FontStyles.Italic; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public class BooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool exists = (bool)value; return exists ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } But most important, is that UserControl.Loaded() has: lbItems.Items.Clear(); lbItems.ItemsSource = fsItems; where fsItems is ObservableCollection<OuterItem>. The usability problem I describe takes place when I Clear() that collection (fsItems) and fill with new items.

    Read the article

  • Merge DataGrid ColumnHeaders

    - by Vishal
    I would like to merge two column-Headers. Before you go and mark this question as duplicate please read further. I don't want a super-Header. I just want to merge two column-headers. Take a look at image below: Can you see two columns with headers Mobile Number 1 and Mobile Number 2? I want to show there only 1 column header as Mobile Numbers. Here is the XAML used for creating above mentioned dataGrid: <DataGrid Grid.Row="1" Margin="0,10,0,0" ItemsSource="{Binding Ledgers}" IsReadOnly="True" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Customer Name" Binding="{Binding LedgerName}" /> <DataGridTextColumn Header="City" Binding="{Binding City}" /> <DataGridTextColumn Header="Mobile Number 1" Binding="{Binding MobileNo1}" /> <DataGridTextColumn Header="Mobile Number 2" Binding="{Binding MobileNo2}" /> <DataGridTextColumn Header="Opening Balance" Binding="{Binding OpeningBalance}" /> </DataGrid.Columns> </DataGrid> Update1: Update2 I have created a converter as follows: public class MobileNumberFormatConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null && value != DependencyProperty.UnsetValue) { if (value.ToString().Length <= 15) { int spacesToAdd = 15 - value.ToString().Length; string s = value.ToString().PadRight(value.ToString().Length + spacesToAdd); return s; } return value.ToString().Substring(0, value.ToString().Length - 3) + "..."; } return ""; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } I have used it in XAML as follows: <DataGridTextColumn Header="Mobile Numbers"> <DataGridTextColumn.Binding> <MultiBinding StringFormat=" {0} {1}"> <Binding Path="MobileNo1" Converter="{StaticResource mobileNumberFormatConverter}"/> <Binding Path="MobileNo2" Converter="{StaticResource mobileNumberFormatConverter}"/> </MultiBinding> </DataGridTextColumn.Binding> </DataGridTextColumn> The output I got: Update3: At last I got the desired output. Here is the code for Converter: public class MobileNumberFormatConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null && value != DependencyProperty.UnsetValue) { if (parameter.ToString().ToUpper() == "N") { if (value.ToString().Length <= 15) { return value.ToString(); } else { return value.ToString().Substring(0, 12); } } else if (parameter.ToString().ToUpper() == "S") { if (value.ToString().Length <= 15) { int spacesToAdd = 15 - value.ToString().Length; string spaces = ""; return spaces.PadRight(spacesToAdd); } else { return "..."; } } } return ""; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } Here is my XAML: <DataGridTemplateColumn Header="Mobile Numbers"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock> <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" /> <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/> <Run Text=" " FontFamily="Consolas"/> <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" /> <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/> </TextBlock> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> Output:

    Read the article

  • Silverlight recursivly bind Treeview to XDocument

    - by Michael Wagner
    How can I recursivly bind a Treeview to an XDocument, mapping each XML Element to a Node in the Treeview? The code below should work from my perspective (and also according to the very few posts I found regarding direct binding), however it does not: <sdk:TreeView ItemsSource="{Binding Path=Elements}" DataContext="{Binding Path=Data}"> <sdk:TreeView.ItemTemplate> <data:HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}"> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Name}"/> </StackPanel> </data:HierarchicalDataTemplate> </sdk:TreeView.ItemTemplate> </sdk:Treeview> (Data is a Property of type XElement on the parents' DataContext) Did I make a mistake somewhere or do I really need to implement an IValueConverter just to get at the child elements of an XElement?

    Read the article

  • WPF Textblock Convert Issue

    - by deep
    am usina text block in usercontrol, but am sending value to textblock from other form, when i pass some value it viewed in textblock, but i need to convert the number to text. so i used converter in textblock. but its not working <TextBlock Height="21" Name="txtStatus" Width="65" Background="Bisque" TextAlignment="Center" Text="{Binding Path=hM1,Converter={StaticResource TextConvert},Mode=OneWay}"/> converter class class TextConvert : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value.ToString() == "1") { return value = "Good"; } if (value.ToString() == "0") { return value = "NIL"; } } return value = ""; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (string)value; } } is it right? whats wrong in it??

    Read the article

  • LevelToVisibilityConverter in silverligt 4

    - by prince23
    <UserControl x:Class="SLGridImage.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"> <UserControl.Resources> <local:LevelToVisibilityConverter x:Key="LevelToVisibility" /> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <sdk:DataGrid x:Name="dgMarks" CanUserResizeColumns="False" SelectionMode="Single" AutoGenerateColumns="False" VerticalAlignment="Top" ItemsSource="{Binding MarkCollection}" IsReadOnly="True" Margin="13,44,0,0" RowDetailsVisibilityMode="Collapsed" Height="391" HorizontalAlignment="Left" Width="965" VerticalScrollBarVisibility="Visible" > <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button x:Name="myButton" Click="myButton_Click"> <StackPanel Orientation="Horizontal"> <Image Margin="2, 2, 2, 2" x:Name="imgMarks" Stretch="Fill" Width="12" Height="12" Source="Images/test.png" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding Level, Converter={StaticResource LevelToVisibility}}" /> <TextBlock Text="{Binding Level}" TextWrapping="NoWrap" ></TextBlock> </StackPanel> </Button> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="Name" > <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate > <Border> <TextBlock Text="{Binding Name}" /> </Border> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="Marks" Width="80"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Border> <TextBlock Text="{Binding Marks}" /> </Border> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> </Grid> </UserControl> in .cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; using System.ComponentModel; namespace SLGridImage { public partial class MainPage : UserControl { private MarksViewModel model = new MarksViewModel(); public MainPage() { InitializeComponent(); this.DataContext = model; } private void myButton_Click(object sender, RoutedEventArgs e) { } } public class MarksViewModel : INotifyPropertyChanged { public MarksViewModel() { markCollection.Add(new Mark() { Name = "ABC", Marks = 23, Level = 0 }); markCollection.Add(new Mark() { Name = "XYZ", Marks = 67, Level = 1 }); markCollection.Add(new Mark() { Name = "YU", Marks = 56, Level = 0 }); markCollection.Add(new Mark() { Name = "AAA", Marks = 89, Level = 1 }); } private ObservableCollection<Mark> markCollection = new ObservableCollection<Mark>(); public ObservableCollection<Mark> MarkCollection { get { return this.markCollection; } set { this.markCollection = value; OnPropertyChanged("MarkCollection"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } public class Mark { public string Name { get; set; } public int Marks { get; set; } public int Level { get; set; } } public class LevelToVisibilityConverter : System.Windows.Data.IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Visibility isVisible = Visibility.Collapsed; if ((value == null)) return isVisible; int condition = (int)value; isVisible = condition == 1 ? Visibility.Visible : Visibility.Collapsed; return isVisible; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } } when i run getting error The type 'local:LevelToVisibilityConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. what i am i missing here looking forward for an solution thank you

    Read the article

  • Silverlight: Binding to static value

    - by queen3
    I need TextBlock.Text to be retrieved from translation manager, something like <TextBlock Text="{Binding TranslateManager.Translate('word')}" /> I don't want to set DataSource for all text blocks. The only way I found how to do this is to bind to "static" class and use converter: <TextBlock Text="{Binding Value, Source={StaticResource Translation}, Converter={StaticResource Translation}, ConverterParameter=NewProject}" /> And these helper class public class TranslationManager : IValueConverter { public static string Translate(string word) { return translate(word); } // this is dummy for fake static binding public string Value { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var name = parameter as string; return TranslationManager.Translate(name, name); } } But, is there a better - shorter - way?

    Read the article

  • Silverlight 3 DataBinding with ValueConverter: conditionally use the default value for property

    - by eriksmith200
    I have a DatePicker for which I want to set the BorderBrush to SolidColorBrush(Colors.Red) if the SelectedDate is null. If a date has been filled in though, I want to just have the default BorderBrush. I still want to be able to style the default BorderBrush in Blend, so I don't want to hardcode the default borderbrush of the DatePicker. So basically: xaml: <controls:DatePicker BorderBrush="{Binding SelectedDate, RelativeSource={RelativeSource Self}, Converter={StaticResource BrushConverter}, Mode=OneWay}"/> c#: public class BrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == null ? new SolidColorBrush(Colors.Red) : /* when value != null have the bound property use it's default value */ } is this possible?

    Read the article

  • ValueConverter not being invoked in DataTemplate binding

    - by unforgiven3
    I have a ComboBox that uses a DataTemplate. The DataTemplate contains a binding which uses an IValueConverter to convert an enumerated value into a string. The problem is that the value converter is never invoked. This is my XAML: <ComboBox ItemsSource="{Binding Path=StatusChoices, Mode=OneWay}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Converter={StaticResource StatusToTextConverter}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> Is my binding not correct? I thought this is how one implicitly binds to the value a DataTemplate is presenting. Am I wrong?

    Read the article

  • XAML Converter ConvertBack

    - by MFH
    Is there a way to access the ConvertBack-Method of a Converter that implements IValueConverter directly from XAML? The basic situation is the following (relationsships): Route (1)<->(CN) Training (1)<->(CN) Kilometer The DataContext is set to a Training. From here I use the Convert-Method to access all my Kilometers. I also have a Converter from Route to IList<Training> and the ConvertBack would lookup the Route for a Training. But I seem to not be able to access that Method from XAML…

    Read the article

  • WPF Databinding and Styling based on Data in an item in an IList

    - by Nate Bross
    I have a ListBox bound to a list of Items (for arguement, lets say its got a string and two dates Entered and Done). I would like to make the background color of items in the ListBox have a gray color if the Done DateTime is != DateTime.MinValue. Edit: Should I make a converter? and convert DateTime to a Brush based on the value of the DateTime? Is something like this my best option? or is there a simple Xaml snippet I could use? [ValueConversion(typeof(DateTime), typeof(Brush))] class MyConverter : IValueConverter { ... }

    Read the article

  • Silverlight Cream for May 02, 2010 -- #854

    - by Dave Campbell
    In this Issue: Michael Washington, Jason Young(-2-, -3-), Phil Middlemiss, Jeremy Likness, Victor Gaudioso, Kunal Chowdhury, Antoni Dol, and Jacek Ciereszko(-2-). Shoutout: Victor Gaudioso has aggregated All of My Silverlight Video Tutorials in One Place (revised again 05.02.10) From SilverlightCream.com: Unit Testing A Silverlight 'Simplified MVVM' Modal Popup Michael Washington's latest 'Simplified MVVM' post is published at The Code Project and is on Unit Testing with MVVM. Input Localization in Silverlight without IValueConverter Jason Young sent me some links to posts I've not seen... this first one is on localization by using the Language property of the Root Visual. MVVM – The Model - Part 1 – INotifyPropertyChanged Jason Young's next archive post is the first of a series on MVVM and Silverlight 4 ... implementing a simple ViewModel base class. Silverlight, WCF, and ASP.Net Configuration Gotchas Jason Young worked at tracking down the answers to some forum questions and in the process has produced a post of 'gotchas' with using WCF in Silverlight. A Chrome and Glass Theme - Part 5 Phil Middlemiss has part 5 of his Chrome and Glass Theme tutorial up ... in this one, he's looking at the Progress Bar and Slider. Download the files and play along. Silverlight Out of Browser (OOB) Versions, Images, and Isolated Storage Jeremy Likness has a post up responding to his 3 major questions about OOB apps, and he has to code up for the sample too. New Silverlight Video Tutorial: How to Make a Slide In/Out Navigation Bar – All in Blend Victor Gaudioso's latest video tutorial is on building a Behavior for a Slide in/out Navigation bar... kinda like the menu sliders on my GlyphMap Utility... only easier! Command Binding in Silverlight 4 (Step-by-Step) Kunal Chowdhury has another post up at DotNetFunda, and this time he's talking about Command Binding in Silverlight 4 with an eye toward MVVM usage. The Silverlight PageCurl implementation Antoni Dol has a post up about doing a Page Curl effect in Silverlight. He has a manual up on the effect and full application code. How to center and scale Silverlight applications using ViewBox control Jacek Ciereszko has a couple posts up about centering and scaling your app with the ViewBox control. This first one is a code solution. Source is available, as is a Polish version. Silverlight Center And Scale Behavior Jacek Ciereszko's 2nd post, he provides a Behavior that handles the scaling and centering of the previous post. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Green (Screen) Computing

    - by onefloridacoder
    I recently was given an assignment to create a UX where a user could use the up and down arrow keys, as well as the tab and enter keys to move through a Silverlight datagrid that is going be used as part of a high throughput data entry UI. And to be honest, I’ve not trapped key codes since I coded JavaScript a few years ago.  Although the frameworks I’m using made it easy, it wasn’t without some trial and error.    The other thing that bothered me was that the customer tossed this into the use case as they were delivering the use case.  Fine.  I’ll take a whack at anything and beat up myself and beg (I’m not beyond begging for help) the community for help to get something done if I have to. It wasn’t as bad as I thought and I thought I would hopefully save someone a few keystrokes if you wanted to build a green screen for your customer.   Here’s the ValueConverter to handle changing the strings to decimals and then back again.  The value is a nullable valuetype so there are few extra steps to take.  Usually the “ConvertBack()” method doesn’t get addressed but in this case we have two-way binding and the converter needs to ensure that if the user doesn’t enter a value it will remain null when the value is reapplied to the model object’s setter.  1: using System; 2: using System.Windows.Data; 3: using System.Globalization; 4:  5: public class NullableDecimalToStringConverter : IValueConverter 6: { 7: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 8: { 9: if (!(((decimal?)value).HasValue)) 10: { 11: return (decimal?)null; 12: } 13: if (!(value is decimal)) 14: { 15: throw new ArgumentException("The value must be of type decimal"); 16: } 17:  18: NumberFormatInfo nfi = culture.NumberFormat; 19: nfi.NumberDecimalDigits = 4; 20:  21: return ((decimal)value).ToString("N", nfi); 22: } 23:  24: public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 25: { 26: decimal nullableDecimal; 27: decimal.TryParse(value.ToString(), out nullableDecimal); 28:  29: return nullableDecimal == 0 ? null : nullableDecimal.ToString(); 30: } 31: }            The ConvertBack() method uses TryParse to create a value from the incoming string so if the parse fails, we get a null value back, which is what we would expect.  But while I was testing I realized that if the user types something like “2..4” instead of “2.4”, TryParse will fail and still return a null.  The user is getting “puuu-lenty” of eye-candy to ensure they know how many values are affected in this particular view. Here’s the XAML code.   This is the simple part, we just have a DataGrid with one column here that’s bound to the the appropriate ViewModel property with the Converter referenced as well. 1: <data:DataGridTextColumn 2: Header="On-Hand" 3: Binding="{Binding Quantity, 4: Mode=TwoWay, 5: Converter={StaticResource DecimalToStringConverter}}" 6: IsReadOnly="False" /> Nothing too magical here.  Just some XAML to hook things up.   Here’s the code behind that’s handling the DataGridKeyup event.  These are wired to a local/private method but could be converted to something the ViewModel could use, but I just need to get this working for now. 1: // Wire up happens in the constructor 2: this.PicDataGrid.KeyUp += (s, e) => this.HandleKeyUp(e);   1: // DataGrid.BeginEdit fires when DataGrid.KeyUp fires. 2: private void HandleKeyUp(KeyEventArgs args) 3: { 4: if (args.Key == Key.Down || 5: args.Key == Key.Up || 6: args.Key == Key.Tab || 7: args.Key == Key.Enter ) 8: { 9: this.PicDataGrid.BeginEdit(); 10: } 11: }   And that’s it.  The ValueConverter was the biggest problem starting out because I was using an existing converter that didn’t take nullable value types into account.   Once the converter was passing back the appropriate value (null, “#.####”) the grid cell(s) and the model objects started working as I needed them to. HTH.

    Read the article

  • WPF binding to ComboBox SelectedItem when reference not in ItemsSource.

    - by juharr
    I'm binding the PageMediaSize collection of a PrintQueue to the ItemSource of a ComboBox (This works fine). Then I'm binding the SelectedItem of the ComboBox to the DefaultPrintTicket.PageMediaSize of the PrintQueue. While this will set the selected value to the DefaultPrintTicket.PageMediaSize just fine it does not set the initially selected value of the ComboBox to the initial value of DefaultPrintTicket.PageMediaSize This is because the DefaultPrintTicket.PageMediaSize reference does not match any of the references in the collection. However I don't want it to compare the objects by reference, but instead by value, but PageMediaSize does not override Equals (and I have no control over it). What I'd really like to do is setup a IComparable for the ComboBox to use, but I don't see any way to do that. I've tried to use a Converter, but I would need more than the value and I couldn't figured out how to pass the collection to the ConverterProperty. Any ideas on how to handle this problem. Here's my xaml <ComboBox x:Name="PaperSizeComboBox" ItemsSource="{Binding ElementName=PrintersComboBox, Path=SelectedItem, Converter={StaticResource printQueueToPageSizesConverter}}" SelectedItem="{Binding ElementName=PrintersComboBox, Path=SelectedItem.DefaultPrintTicket.PageMediaSize}" DisplayMemberPath="PageMediaSizeName" Height="22" Margin="120,76,15,0" VerticalAlignment="Top"/> And the code for the converter that gets the PageMediaSize collection public class PrintQueueToPageSizesConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value == null ? null : ((PrintQueue)value).GetPrintCapabilities().PageMediaSizeCapability; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }

    Read the article

  • Dependency Property on ValueConverter

    - by spoon16
    I'm trying to initialize a converter in the Resources section of my UserControl with a reference to one of the objects in my control. When I try to run the application I get an XAML parse exception. XAML: <UserControl.Resources> <converter:PointConverter x:Key="pointConverter" Map="{Binding ElementName=ThingMap}" /> </UserControl.Resources> <Grid> <m:Map x:Name="ThingMap" /> </Grid> Point Converter Class: public class PointConverter : DependencyObject, IValueConverter { public Microsoft.Maps.MapControl.Map Map { get { return (Microsoft.Maps.MapControl.Map)GetValue(MapProperty); } set { SetValue(MapProperty, value); } } // Using a DependencyProperty as the backing store for Map. This enables animation, styling, binding, etc... public static readonly DependencyProperty MapProperty = DependencyProperty.Register("Map", typeof(Microsoft.Maps.MapControl.Map), typeof(PointConverter), null); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string param = (string)parameter; Microsoft.Maps.MapControl.Location location = value as Microsoft.Maps.MapControl.Location; if (location != null) { Point point = Map.LocationToViewportPoint(location); if (string.Compare(param.ToUpper(), "X") == 0) return point.X; else if (string.Compare(param.ToUpper(), "Y") == 0) return point.Y; return point; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }

    Read the article

< Previous Page | 1 2 3  | Next Page >