Search Results

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

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

  • Two Way Data Binding With a Object in WPF,Image Control

    - by Candy
    Sorry, my English is not very good, I have a object "Stuffs" "Stuffs" have a Property “Icon” now: xaml <Button Click="Button_Click"><Image Width="80" Height="80" Source="{Binding Path=Icon,Converter={StaticResource ImageConverter}}"/></Button> cs private void Button_Click(object sender, RoutedEventArgs e) { IconFloder.Title = "Icon"; String IconFloderPath = AppDomain.CurrentDomain.BaseDirectory + ItemIconFloder; if (!System.IO.Directory.Exists(IconFloderPath)) System.IO.Directory.CreateDirectory(IconFloderPath); IconFloder.InitialDirectory = IconFloderPath; IconFloder.Filter = "Image File|*.jpeg"; IconFloder.ValidateNames = true; IconFloder.CheckPathExists = true; IconFloder.CheckFileExists = true; if (IconFloder.ShowDialog() == true) { HideImage.Text = ItemIconFloder + "\\" + IconFloder.SafeFileName; ((sender as Button).Content as Image).Source = new ImageConverter().Convert(ItemIconFloder + "\\" + IconFloder.SafeFileName, Type.GetType("System.Windows.Media.ImageSource"), null, new System.Globalization.CultureInfo("en-US")) as ImageSource; } } class ImageConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string&&!String.IsNullOrEmpty(value.ToString())) { try { return new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + value)); } catch { } } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } I would like to click buttons, change the picture, Also change Data Binding Stuffs.Icon But failed,I have no idea?I need help? I do not know whether I speak clearly

    Read the article

  • Get the value for a WPF binding

    - by Jose
    Ok, I didn't want a bunch of ICommands in my MVVM ViewModels so I decided to create a MarkupExtension for WPF that you feed it a string(the name of the method), and it gives you back an ICommand that executes the method. here's a snippet: public class MethodCall : MarkupExtension { public MethodCall(string methodName) { MethodName = methodName; CanExecute = "Can" + methodName; } public override object ProvideValue(IServiceProvider serviceProvider) { Binding bin= new Binding { Converter = new MethodConverter(MethodName,CanExecute) }; return bin.ProvideValue(serviceProvider); } } public class MethodConverter : IValueConverter { string MethodName; public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //Convert to ICommand ICommand cmd = ConvertToICommand(); if (cmd == null) Debug.WriteLine(string.Format("Could not bind to method 'MyMethod' on object",MethodName)); return cmd; } } It works great, except when the binding fails(e.g. you mistype). When you do this in xaml: {Binding MyPropertyName} you see in the output window whenever the binding fails. and it tells you the propertyName the Type name etc. The MethodConverter Class can tell you the name of the method that failed, but it can't tell you the source object type. Because the value will be null. I can't figure out how to store the source object type so for the following class public class MyClass { public void MyMethod() { } } and the following xaml: <Button Command={d:MethodCall MyMethod}>My Method</Button> It currently says: "Could not bind to method 'MyMethod' on object but I would like it to say: "Could not bind to method 'MyMethod' on object MyClass Any ideas?

    Read the article

  • Button Visibility Converter

    - by developer
    Hi All, I have a requirement wherein I need to display on a User form, a Create Button if that user has doesnt have a profile and a Edit Button if he does have a profile. I am using a converter to change the visibility of the button. Below is my code, <StackPanel Orientation="Horizontal"> <Button Content="Create Profile" Visibility="{Binding Profile,Converter={StaticResource ButtonVisibilityConverter}, ConverterParameter='Create'}" Command="local:LaunchEditor" CommandParameter="{Binding}"/> <Button Content="Edit Profile" Visibility="{Binding Profile,Converter={StaticResource ButtonVisibilityConverter}, ConverterParameter='Edit'}" Command="local:LaunchEditor" CommandParameter="{Binding}"/> </StackPanel> Below is my converter code public class ButtonVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string btName = null; btName = (string)parameter; if ((value==null)&&(btName=="Create")) { return Visibility.Visible; } else if ((value != null) && (btName=="Edit")) { return Visibility.Visible; } else { return Visibility.Collapsed; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Everything works fine initially, but the moment I click on the Create Profile window, and it is the constructor that loads the profile window, after that even if I close that window without doing anything, the Create button turns to edit. My guess is that, it is because the constructor would have create the profile object and so even though the object is empty it shows me edit button instead of create. Is there any other way I could display button visibility??

    Read the article

  • lighten background color on button click per binding

    - by one of two
    I want to lighten a buttons background on click. So I did the following: <converter:ColorLightConverter x:Key="colorLightConverter" /> ... <Style BasedOn="{StaticResource default}" TargetType="{x:Type controls:Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type controls:Button}"> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background"> <Setter.Value> <SolidColorBrush Color="{Binding Path=Background.Color, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource colorLightConverter}}" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> <Border Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0"> ... </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> The converter: class ColorLightConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Color color = (Color)value; System.Drawing.Color lightColor = ControlPaint.Light(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B)); return Color.FromArgb(lightColor.A, lightColor.R, lightColor.G, lightColor.B); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } But the converter isn't called when I click the button. I think there is anything wrong with the binding, but I can't see the error... Can you help me? Maybe I'm completely wrong. What I basically want to do: When clicking the button, take the current background color and lighten it. Not more...

    Read the article

  • binding image with 2 values with convertor

    - by prince23
    hi, is it possiable to set 2 data field for an image control whiling binding **<Image Source="{Binding ItemID, Converter={StaticResource IDToImageConverter}}" Height="50" />** now here i need to add one more value Price now. need to send even price as an paramter for IDToImageConverter function how can i do it? now i need to check first price value there are 3 condition i neeed to check in my IDToImageConverter function if( price> 5o) { // then get the ItemID based on the value bind image here if(ItemID >20) { // bind image1 } if(ItemID >50) { // bind image2 } } if( price> 100) { // as above codition we do here } now how can i add these above functionality in IDToImageConverter ? any idea how i can solve it <Image Source="{Binding ItemID, Converter={StaticResource IDToImageConverter}}" Height="50" /> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> public class IDToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Uri uri = new Uri("~/Images/" + value.ToString()+ ".jpg", UriKind.Relative); return new BitmapImage(uri); } thanks in advance. for anyhelp you provide prince

    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

  • Using embedded resources in Silverlight (4) - other cultures not being compiled

    - by Andrei Rinea
    I am having a bit of a hard time providing localized strings for the UI in a small Silverlight 4 application. Basically I've put a folder "Resources" and placed two resource files in it : Statuses.resx Statuses.ro.resx I do have an enum Statuses : public enum Statuses { None, Working } and a convertor : public class StatusToMessage : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!Enum.IsDefined(typeof(Status), value)) { throw new ArgumentOutOfRangeException("value"); } var x = Statuses.None; return Statuses.ResourceManager.GetString(((Status)value).ToString(), Thread.CurrentThread.CurrentUICulture); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } in the view I have a textblock : <TextBlock Grid.Column="3" Text="{Binding Status, Converter={StaticResource StatusToMessage}}" /> Upon view rendering the converter is called but no matter what the Thread.CurrentThread.CurrentUICulture is set it always returns the default culture value. Upon further inspection I took apart the XAP resulted file, taken the resulted DLL file to Reflector and inspected the embedded resources. It only contains the default resource!! Going back to the two resource files I am now inspecting their properties : Build action : Embedded Resource Copy to output directory : Do not copy Custom tool : ResXFileCodeGenerator Custom tool namespace : [empty] Both resource (.resx) files have these settings. The .Designer.cs resulted files are as follows : Statuses.Designer.cs : //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SilverlightApplication5.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Statuses { // ... yadda-yadda Statuses.ro.Designer.cs [empty] I've taken both files and put them in a console application and they behave as expected in it, not like in this silverlight application. What is wrong?

    Read the article

  • Bind listbox in WPF with grouping

    - by Michael Stoll
    Hi, I've got a collection of ViewModels and want to bind a ListBox to them. Doing some investigation I found this. So my ViewModel look like this (Pseudo Code) interface IItemViewModel { string DisplayName { get; } } class AViewModel : IItemViewModel { string DisplayName { return "foo"; } } class BViewModel : IItemViewModel { string DisplayName { return "foo"; } } class ParentViewModel { IEnumerable<IItemViewModel> Items { get { return new IItemViewModel[] { new AItemViewModel(), new BItemViewModel() } } } } class GroupViewModel { static readonly GroupViewModel GroupA = new GroupViewModel(0); static readonly GroupViewModel GroupB = new GroupViewModel(1); int GroupIndex; GroupViewModel(int groupIndex) { this.GroupIndex = groupIndex; } string DisplayName { get { return "This is group " + GroupIndex.ToString(); } } } class ItemGroupTypeConverter : IValueConverter { object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is AItemViewModel) return GroupViewModel.GroupA; else return GroupViewModel.GroupB; } } And this XAML <UserControl.Resources> <vm:ItemsGroupTypeConverter x:Key="ItemsGroupTypeConverter "/> <CollectionViewSource x:Key="GroupedItems" Source="{Binding Items}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription Converter="{StaticResource ItemsGroupTypeConverter }"/> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </UserControl.Resources> <ListBox ItemsSource="{Binding Source={StaticResource GroupedItems}}"> <ListBox.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding DisplayName}" FontWeight="bold" /> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle> </ListBox.GroupStyle> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding DisplayName}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> This works somehow, exept of the fact that the binding of the HeaderTemplate does not work. Anyhow I'd prefer omitting the TypeConverter and the CollectionViewSource. Isn't there a way to use a property of the ViewModel for Grouping? I know that in this sample scenario it would be easy to replace the GroupViewModel with a string an have it working, but that's not an option. So how can I bind the HeaderTemplate to the GroupViewModel?

    Read the article

  • WPF MVVM: Convention over Configuration for ResourceDictionary ?

    - by Jeffrey Knight
    Update In the wiki spirit of StackOverflow, here's an update: I spiked Joe White's IValueConverter suggestion below. It works like a charm. I've written a "quickstart" example of this that automates the mapping of ViewModels-Views using some cheap string replacement. If no View is found to represent the ViewModel, it defaults to an "Under Construction" page. I'm dubbing this approach "WPF MVVM White" since it was Joe White's idea. Here are a couple screenshots. The first image is a case of "[SomeControlName]ViewModel" has a corresponding "[SomeControlName]View", based on pure naming convention. The second is a case where the ModelView doesn't have any views to represent it. No more ResourceDictionaries with long ViewModel to View mappings. It's pure naming convention now. I'm hosting a download of the project here: http://rootsilver.com/files/Mvvm.White.Quickstart.zip I'll follow up with a longer blog post walk through. Original Post I read Josh Smith's fantastic MSDN article on WPF MVVM over the weekend. It's destined to be a cult classic. It took me a while to wrap my head around the magic of asking WPF to render the ViewModel. It's like saying "Here's a class, WPF. Go figure out which UI to use to present it." For those who missed this magic, WPF can do this by looking up the View for ModelView in the ResourceDictionary mapping and pulling out the corresponding View. (Scroll down to Figure 10 Supplying a View ). The first thing that jumps out at me immediately is that there's already a strong naming convention of: classNameView ("View" suffix) classNameViewModel ("ViewModel" suffix) My question is: Since the ResourceDictionary can be manipulated programatically, I"m wondering if anyone has managed to Regex.Replace the whole thing away, so the lookup is automatic, and any new View/ViewModels get resolved by virtue of their naming convention? [Edit] What I'm imagining is a hook/interception into ResourceDictionary. ... Also considering a method at startup that uses interop to pull out *View$ and *ViewModel$ class names to build the DataTemplate dictionary in code: //build list foreach .... String.Format("<DataTemplate DataType=\"{x:Type vm:{0} }\"><v:{1} /></DataTemplate>", ...)

    Read the article

  • TemplateBinding with Converter - what is wrong?

    - by MartyIX
    I'm creating a game desk. I wanted to specify field size (one field is a square) as a attached property and with this data set value of ViewPort which would draw 2x2 matrix (and tile mode would do the rest of game desk). I'm quite at loss what is wrong because the binding doesn't work. Testing line in XAML for the behaviour I would like to have: <DrawingBrush Viewport="0,0,100,100" ViewportUnits="Absolute" TileMode="None"> The game desk is based on this sample of DrawingPaint: http://msdn.microsoft.com/en-us/library/aa970904.aspx (an image is here) XAML: <Window x:Class="Sokoban.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Sokoban" Title="Window1" Height="559" Width="419"> <Window.Resources> <local:FieldSizeToRectConverter x:Key="fieldSizeConverter" /> <Style x:Key="GameDesk" TargetType="{x:Type Rectangle}"> <Setter Property="local:GameDeskProperties.FieldSize" Value="50" /> <Setter Property="Fill"> <Setter.Value> <!--<DrawingBrush Viewport="0,0,100,100" ViewportUnits="Absolute" TileMode="None">--> <DrawingBrush Viewport="{TemplateBinding local:GameDeskProperties.FieldSize, Converter={StaticResource fieldSizeConverter}}" ViewportUnits="Absolute" TileMode="None"> <DrawingBrush.Drawing> <DrawingGroup> <GeometryDrawing Brush="CornflowerBlue"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,100,100" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="Azure"> <GeometryDrawing.Geometry> <GeometryGroup> <RectangleGeometry Rect="0,0,50,50" /> <RectangleGeometry Rect="50,50,50,50" /> </GeometryGroup> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> </Setter.Value> </Setter> </Style> </Window.Resources> <StackPanel> <Rectangle Style="{StaticResource GameDesk}" Width="300" Height="150" /> </StackPanel> </Window> Converter and property definition: using System; using System.Collections.Generic; using System.Text; using System.Windows.Controls; using System.Windows; using System.Diagnostics; using System.Windows.Data; namespace Sokoban { public class GameDeskProperties : Panel { public static readonly DependencyProperty FieldSizeProperty; static GameDeskProperties() { PropertyChangedCallback fieldSizeChanged = new PropertyChangedCallback(OnFieldSizeChanged); PropertyMetadata fieldSizeMetadata = new PropertyMetadata(50, fieldSizeChanged); FieldSizeProperty = DependencyProperty.RegisterAttached("FieldSize", typeof(int), typeof(GameDeskProperties), fieldSizeMetadata); } public static int GetFieldSize(DependencyObject target) { return (int)target.GetValue(FieldSizeProperty); } public static void SetFieldSize(DependencyObject target, int value) { target.SetValue(FieldSizeProperty, value); } static void OnFieldSizeChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("FieldSize just changed: " + e.NewValue); } } [ValueConversion(/* sourceType */ typeof(int), /* targetType */ typeof(Rect))] public class FieldSizeToRectConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Debug.Assert(targetType == typeof(int)); int fieldSize = int.Parse(value.ToString()); return new Rect(0, 0, 2 * fieldSize, 2 * fieldSize); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // should not be called in our example throw new NotImplementedException(); } } }

    Read the article

  • Formatting Telerik Chart and Legend Labels in Silverlight

    - by Bryan
    I am trying to format a column called 'Month' using the 3-character month abbreviation in my data grid which is bound to a bar chart. My grid and chart are based on this demo example: http://demos.telerik.com/silverlight/#Chart/Aggregates. Basically, the grid compiles data and summarizes by Year, Quarter, Month, and then some other categories as well. For the Month column, I tried two different methods (for sorting purposes, I have to use an integer or some date value for the month). First, I just made Month an integer field and then used a converter mapped in the xaml for the 'Month' field to display 'JAN', 'FEB', etc. This worked fine for the grid, but the chart would display 1, 2, etc. instead of the month abbreviation. I researched this and was not able to come up with a solution to map the converter to the chart. So, I tried making the Month field a datetime and then set the value to 1/1/1900, 2/1/1900, etc. and specified the format of the field to 'MMM' in the xaml for the grid. I then used the following statement to set the the format in the chart when the user grouped by month: SalesAnalysisChart.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "MMM"; This partially worked in that when the months were displayed across the x-axis they were labeled properly, but not when they appeared in the legend (the user, of course, can group by any of the columns which may or may not include month). I've tried setting LegendItemLabelFormat, ItemLabelFormat, etc. but without success. I'm not sure of the element on which to set the property. I only need to change the default format for just the Month column - all other columns should display normally when grouped. I also came across a class called 'LegendItemFormatConverter' which looks promising but I can't find any examples as to how to implement it. I would actually prefer the converter method because the converter I wrote displays the month abbreviation in all caps, whereas the 'MMM' format displays in upper/lower case. Here is the converter code that I originally used for the grid: using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Data; namespace ApolloSL { public class MonthConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null) { DateTime date = new DateTime(1900, (Int32)value, 1); return date.ToString("MMM").ToUpper(); } else { return ""; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.ToString(); } } } Please help... Thanks in advance for your assistance, Bryan

    Read the article

  • listbox isSelected databinding in DataTemplate

    - by Kinmarui
    I try to simply databind IsSelected property with IsSelected field in my class. But after I change the value in code its doesn't change the property, neither does clicking on ListBoxItem change the field value. XAML: <FlipView ItemsSource="{Binding Source={StaticResource itemsViewSource}}" ... > <FlipView.ItemTemplate> <DataTemplate> <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates"> <!-- other controls --> <ListBox Grid.Row="1" Grid.ColumnSpan="3" SelectionMode="Multiple" VerticalAlignment="Center" ItemsSource="{Binding Answers}"> <ListBox.Resources> <local:LogicToText x:Key="logToText" /> </ListBox.Resources> <!-- bind IsSelected only in one way from code to content --> <ItemsControl.ItemTemplate> <DataTemplate> <ListBoxItem IsSelected="{Binding IsSelected, Mode=TwoWay, Converter={StaticResource logToText}}" Content="{Binding IsSelected, Mode=TwoWay, Converter={StaticResource logToText}}"> </ListBoxItem> </DataTemplate> </ItemsControl.ItemTemplate> <!-- not working at all <ListBox.Resources> <Style TargetType="ListBoxItem"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> <Setter Property="Content" Value="{Binding IsSelected, Mode=TwoWay}"/> </Style> </ListBox.Resources>--> </ListBox> </UserControl> </DataTemplate> </FlipView.ItemTemplate> </FlipView> Code: Answers private ObservableCollection<PrawoJazdyDataAnswer> _answers = new ObservableCollection<PrawoJazdyDataAnswer>(); public ObservableCollection<PrawoJazdyDataAnswer> Answers { get { return this._answers; } } Single item(Answer) public class PrawoJazdyDataAnswer : NPCHelper// PrawoJazdy.Common.BindableBase { public PrawoJazdyDataAnswer(String ans, bool ansb) { this._ans = ans; this._isSelected = ansb; } public override string ToString() { return _isSelected.ToString(); } //Only For debug purposes normally return _ans; private string _ans; public string Ans { get { return this._ans; } //set { this.SetProperty(ref this._ans, value); } } private bool _isSelected; public bool IsSelected { get { return this._isSelected; } set { _isSelected = value; FirePropertyChanged("IsSelected"); //this.SetProperty(ref this._isSelected, value); } } } FirePropertyChanged public class NPCHelper : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void FirePropertyChanged(string prop) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } Converter(which sometimes seems to be needed and others not..., I tried ~10 approaches from different tutorials/examples) public class LogicToText : IValueConverter { /// <summary> /// /// </summary> public object Convert(object value, Type targetType, object parameter, string language) { //if (value == null || (bool)value == false) // return "False"; return value.ToString(); } /// <summary> /// /// </summary> public object ConvertBack(object value, Type targetType, object parameter, string language) { return value.ToString().Contains("True") ? true : false; } Thanks in advance, and sorry for my English(still learning). @edit Thanks for quick reply. For test purposes i created a button and text block: It's in other controls part (above list box, but in FlipView) <Button Click="spr" >Sprawdz</Button> <TextBlock Text="{Binding Answers[0].IsSelected, Mode=TwoWay}" > </TextBlock> Click method private void spr(object sender, RoutedEventArgs e) { var ans = ((PrawoJazdyDataQuestion)this.flipView.SelectedItem).Answers; foreach (var item in ans) item.IsSelected = item.IsSelected ? false : true; } As I wrote when i'm changing data from code side its change text, but not appearance of ListBoxItem, and if i just select it on ListBox its doesn't change the date i textblock neither in ListBox itself.

    Read the article

  • WPF TreeView MouseDown

    - by imekon
    I've got something like this in a TreeView: <DataTemplate x:Key="myTemplate"> <StackPanel MouseDown="OnItemMouseDown"> ... </StackPanel> </DataTemplate> Using this I get the mouse down events if I click on items in the stack panel. However... there seems to be another item behind the stack panel that is the TreeViewItem - it's very hard to hit, but not impossible, and that's when the problems start to occur. I had a go at handling PreviewMouseDown on TreeViewItem, however that seems to require e.Handled = false otherwise standard tree view behaviour stops working. Ok, Here's the source code... MainWindow.xaml <Window x:Class="WPFMultiSelectTree.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFMultiSelectTree" Title="Multiple Selection Tree" Height="300" Width="300"> <Window.Resources> <!-- Declare the classes that convert bool to Visibility --> <local:VisibilityConverter x:Key="visibilityConverter"/> <local:VisibilityInverter x:Key="visibilityInverter"/> <!-- Set the style for any tree view item --> <Style TargetType="TreeViewItem"> <Style.Triggers> <DataTrigger Binding="{Binding Selected}" Value="True"> <Setter Property="Background" Value="DarkBlue"/> <Setter Property="Foreground" Value="White"/> </DataTrigger> </Style.Triggers> <EventSetter Event="PreviewMouseDown" Handler="OnTreePreviewMouseDown"/> </Style> <!-- Declare a hierarchical data template for the tree view items --> <HierarchicalDataTemplate x:Key="RecursiveTemplate" ItemsSource="{Binding Children}"> <StackPanel Margin="2" Orientation="Horizontal" MouseDown="OnTreeMouseDown"> <Ellipse Width="12" Height="12" Fill="Green"/> <TextBlock Margin="2" Text="{Binding Name}" Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"/> <TextBox Margin="2" Text="{Binding Name}" KeyDown="OnTextBoxKeyDown" IsVisibleChanged="OnTextBoxIsVisibleChanged" Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"/> <TextBlock Margin="2" Text="{Binding Index, StringFormat=({0})}"/> </StackPanel> </HierarchicalDataTemplate> <!-- Declare a simple template for a list box --> <DataTemplate x:Key="ListTemplate"> <TextBlock Text="{Binding Name}"/> </DataTemplate> </Window.Resources> <Grid> <!-- Declare the rows in this grid --> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <!-- The first header --> <TextBlock Grid.Row="0" Margin="5" Background="PowderBlue">Multiple selection tree view</TextBlock> <!-- The tree view --> <TreeView Name="m_tree" Margin="2" Grid.Row="1" ItemsSource="{Binding Children}" ItemTemplate="{StaticResource RecursiveTemplate}"/> <!-- The second header --> <TextBlock Grid.Row="2" Margin="5" Background="PowderBlue">The currently selected items in the tree</TextBlock> <!-- The list box --> <ListBox Name="m_list" Margin="2" Grid.Row="3" ItemsSource="{Binding .}" ItemTemplate="{StaticResource ListTemplate}"/> </Grid> </Window> MainWindow.xaml.cs /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Container m_root; private Container m_first; private ObservableCollection<Container> m_selection; private string m_current; /// <summary> /// Constructor /// </summary> public MainWindow() { InitializeComponent(); m_selection = new ObservableCollection<Container>(); m_root = new Container("root"); for (int parents = 0; parents < 50; parents++) { Container parent = new Container(String.Format("parent{0}", parents + 1)); for (int children = 0; children < 1000; children++) { parent.Add(new Container(String.Format("child{0}", children + 1))); } m_root.Add(parent); } m_tree.DataContext = m_root; m_list.DataContext = m_selection; m_first = null; } /// <summary> /// Has the shift key been pressed? /// </summary> private bool ShiftPressed { get { return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift); } } /// <summary> /// Has the control key been pressed? /// </summary> private bool CtrlPressed { get { return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); } } /// <summary> /// Clear down the selection list /// </summary> private void DeselectAndClear() { foreach(Container container in m_selection) { container.Selected = false; } m_selection.Clear(); } /// <summary> /// Add the container to the list (if not already present), /// mark as selected /// </summary> /// <param name="container"></param> private void AddToSelection(Container container) { if (container == null) { return; } foreach (Container child in m_selection) { if (child == container) { return; } } container.Selected = true; m_selection.Add(container); } /// <summary> /// Remove container from list, mark as not selected /// </summary> /// <param name="container"></param> private void RemoveFromSelection(Container container) { m_selection.Remove(container); container.Selected = false; } /// <summary> /// Process single click on a tree item /// /// Normally just select an item /// /// SHIFT-Click extends selection /// CTRL-Click toggles a selection /// </summary> /// <param name="sender"></param> private void OnTreeSingleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { if (CtrlPressed) { if (container.Selected) { RemoveFromSelection(container); } else { AddToSelection(container); } } else if (ShiftPressed) { if (container.Parent == m_first.Parent) { if (container.Index < m_first.Index) { Container item = container; for (int i = container.Index; i < m_first.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } else if (container.Index > m_first.Index) { Container item = m_first; for (int i = m_first.Index; i <= container.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } } } else { DeselectAndClear(); m_first = container; AddToSelection(container); } } } } /// <summary> /// Process double click on tree item /// </summary> /// <param name="sender"></param> private void OnTreeDoubleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { container.Editing = true; m_current = container.Name; } } } /// <summary> /// Clicked on the stack panel in the tree view /// /// Double left click: /// /// Switch to editing mode (flips visibility of textblock and textbox) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreeMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("StackPanel mouse down"); switch(e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 2: OnTreeDoubleClick(sender); e.Handled = true; break; } break; } } /// <summary> /// Clicked on tree view item in tree /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreePreviewMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("TreeViewItem preview mouse down"); switch (e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 1: { // We've had a single click on a tree view item // Unfortunately this is the WHOLE tree item, including the +/- // symbol to the left. The tree doesn't do a selection, so we // have to filter this out... MouseDevice device = e.Device as MouseDevice; Debug.WriteLine(String.Format("Tree item clicked on: {0}", device.DirectlyOver.GetType().ToString())); // This is bad. The whole point of WPF is for the code // not to know what the UI has - yet here we are testing for // it as a workaround. Sigh... if (device.DirectlyOver.GetType() != typeof(Path)) { OnTreeSingleClick(sender); } // Cannot say handled - if we do it stops the tree working! //e.Handled = true; } break; } break; } } /// <summary> /// Key press in text box /// /// Return key finishes editing /// Escape key finishes editing, restores original value (this doesn't work!) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Return: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; e.Handled = true; } } } break; case Key.Escape: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; container.Name = m_current; e.Handled = true; } } } break; } } /// <summary> /// When text box becomes visible, grab focus and select all text in it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { bool visible = (bool)e.NewValue; if (visible) { TextBox box = sender as TextBox; if (box != null) { box.Focus(); box.SelectAll(); } } } } Here's the Container class public class Container : INotifyPropertyChanged { private string m_name; private ObservableCollection<Container> m_children; private Container m_parent; private bool m_selected; private bool m_editing; /// <summary> /// Constructor /// </summary> /// <param name="name">name of object</param> public Container(string name) { m_name = name; m_children = new ObservableCollection<Container>(); m_parent = null; m_selected = false; m_editing = false; } /// <summary> /// Name of object /// </summary> public string Name { get { return m_name; } set { if (m_name != value) { m_name = value; OnPropertyChanged("Name"); } } } /// <summary> /// Index of object in parent's children /// /// If there's no parent, the index is -1 /// </summary> public int Index { get { if (m_parent != null) { return m_parent.Children.IndexOf(this); } return -1; } } /// <summary> /// Get the next item, assuming this is parented /// /// Returns null if end of list reached, or no parent /// </summary> public Container Next { get { if (m_parent != null) { int index = Index + 1; if (index < m_parent.Children.Count) { return m_parent.Children[index]; } } return null; } } /// <summary> /// List of children /// </summary> public ObservableCollection<Container> Children { get { return m_children; } } /// <summary> /// Selected status /// </summary> public bool Selected { get { return m_selected; } set { if (m_selected != value) { m_selected = value; OnPropertyChanged("Selected"); } } } /// <summary> /// Editing status /// </summary> public bool Editing { get { return m_editing; } set { if (m_editing != value) { m_editing = value; OnPropertyChanged("Editing"); } } } /// <summary> /// Parent of this object /// </summary> public Container Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// WPF Property Changed event /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Handler to inform WPF that a property has changed /// </summary> /// <param name="name"></param> private void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } /// <summary> /// Add a child to this container /// </summary> /// <param name="child"></param> public void Add(Container child) { m_children.Add(child); child.m_parent = this; } /// <summary> /// Remove a child from this container /// </summary> /// <param name="child"></param> public void Remove(Container child) { m_children.Remove(child); child.m_parent = null; } } The two classes VisibilityConverter and VisibilityInverter are implementations of IValueConverter that translates bool to Visibility. They make sure the TextBlock is displayed when not editing, and the TextBox is displayed when editing.

    Read the article

< Previous Page | 1 2 3