Search Results

Search found 1226 results on 50 pages for 'kendo mvvm'.

Page 22/50 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • RelayCommand sender from ItemsControl item

    - by Padu Merloti
    I've been using MVVM's RelayCommand with success to bind actions to XAML, but I'm having a small problem with my ItemsControl. <ItemsControl ItemsSource="{Binding Devices}" > <ItemsControl.ItemTemplate> <DataTemplate> <Grid Width="100" Margin="4" > <Button Command="{Binding Path=SelectDeviceCommand}" > <Grid> <Image Source="img_small.png"></Image> <Image Source="{Binding Path=Logo}" /> </Grid> </Button> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> In my view model: public RelayCommand SelectDeviceCommand { get; set; } private ObservableCollection<Device> Devices; Devices = CreateListOfDevices(); private void InitializeCommands() { SelectDeviceCommand = new RelayCommand((s) => MessageBox.Show(s.ToString())); } How do I define my SelectDeviceCommand in my view model in order to receive object that is bound to that item? My SelectDeviceCommand is not even being called... (but that I guess is because I need to make my Device a mini-viewmodel and implement the SelectDeviceCommand in it, is that correct?)

    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

  • ViewModel updates after Model server roundtrip

    - by Pavel Savara
    I have stateless services and anemic domain objects on server side. Model between server and client is POCO DTO. The client should become MVVM. The model could be graph of about 100 instances of 20 different classes. The client editor contains diverse tab-pages all of them live-connected to model/viewmodel. My problem is how to propagate changes after server round-trip nice way. It's quite easy to propagate changes from ViewModel to DTO. For way back it would be possible to throw away old DTO and replace it whole with new one, but it will cause lot of redrawing for lists/DataTemplates. I could gather the server side changes and transmit them to client side. But the names of fields changed would be domain/DTO specific, not ViewModel specific. And the mapping seems nontrivial to me. If I should do it imperative way after round-trip, it would break SOC/modularity of viewModels. I'm thinking about some kind of mapping rule engine, something like automappper or emit mapper. But it solves just very plain use-cases. I don't see how it would map/propagate/convert adding items to list or removal. How to identify instances in collections so it could merge values to existing instances. As well it should propagate validation/error info. Maybe I should implement INotifyPropertyChanged on DTO and try to replay server side events on it ? And then bind ViewModel to it ? Would binding solve the problems with collection merges nice way ? Is EventAgregator from PRISM useful for that ? Is there any event record-replay component ? Is there better client side pattern for architecture with server side logic ?

    Read the article

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

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

    Read the article

  • TextBox should display text in hexadecimal in a specific format

    - by Owais Wani
    I have a textbox in my xaml file which is editable. Now according to my project requirements content in textbox should only be 0-9 and a-f (hexadecimal values) and textbox should take the input based on hexadecimal values. Demonstratation: 12 ab 32 a5 64 Now if my cursor is at the end and i go on pressing backspace, it shud remove the values as it happens in a general text box. Now If my cursor is at the beginning of a5, and i press "delete key", the value should become like: 12 ab 32 56 4 If my cursor is at the end of a5 and i press the 'delete key" nothing should happen. I had done this successful in my C++ application as follows: void CMSP430CommPanel::textEditorTextChanged (TextEditor& editor) { if(&editor == m_texti2cWrite) { int count = 0; int location; String text1 = m_texti2cWrite->getText(); String text = m_texti2cWrite->getText().removeCharacters(" "); String hexString = String::empty; int countCaret = m_texti2cWrite->getCaretPosition(); for(int i=0; i < text.length(); i++) { hexString = hexString + String (&text[i], 1); if((i+1) % 2 == 0) { if(i != text.length()-1) { hexString = hexString + T(" "); count ++; } } count ++; } m_texti2cWrite->setText(hexString,false); if(text1.length() == m_texti2cWrite->getCaretPosition()) { m_texti2cWrite->setCaretPosition(count); } else { m_texti2cWrite->setCaretPosition(countCaret); } } } where m_texti2cWrite is the name given to textbox. How can i implement the same case in my wpf application which is MVVM based. I have a textbox which shud take inputs as I said above. please help!!!

    Read the article

  • How do I stop ValueConverters from firing when swapping the content of a ContentControl

    - by DanM
    I thought what I was doing was right out of the Josh Smith MVVM handbook, but I seem to be having a lot of problems with value converters firing when no data in the view-model has changed. So, I have a ContentControl defined in XAML like this: <ContentControl Grid.Row="0" Content="{Binding CurrentViewModel}" /> The Window containing this ContentControl references a resource dictionary that looks something like this: <ResourceDictionary ...> <DataTemplate DataType="{x:Type lib_vm:SetupPanelViewModel}"> <lib_v:SetupPanel /> </DataTemplate> <DataTemplate DataType="{x:Type lib_vm:InstructionsPanelViewModel}"> <lib_v:InstructionsPanel /> </DataTemplate> </ResourceDictionary> So, basically, the two data templates specify which view to show with which view-model. This switches the views as expected whenever the CurrentViewModel property on my window's view-model changes, but it also seems to cause value converters on the views to fire even when no data has changed. It's a particular problem with IMultiValueConverter classes, because the values in the value array get set to DependencyProperty.UnsetValue, which causes exceptions unless I specifically check for that. But I'm getting other weird side effects too. This has me wondering if I shouldn't just do everything manually, like this: Instantiate each view. Set the DataContext of each view to the appropriate view-model. Give the ContentControl a name and make it public. Handle the PropertyChanged event for the window. In the event handler, manually set the Content property of the ContentControl to the appropriate view, based the CurrentViewModel (using if statements). This seems to work, but it also seems very inelegant. I'm hoping there's a better way. Could you please advise me the best way to handle view switching so that value converters don't fire unnecessarily?

    Read the article

  • Where to Store ID Field In Silverlight

    - by Blake Blackwell
    I am trying to use the MVVM pattern, and I am wondering where I place an ID value. Do I create a TextBlock that has its visibility property set to collapsed? Or is there a better place to store this kind of data? Currently the command parameter is set to: CommandParameter="{Binding ElementName=Name,Path=Text}" But I'd rather it be something like: CommandParameter="{Binding ElementName=Id,Path=Text}" I'm totally up for suggestions on what the best way there is to do this, since I'm new to this pattern and presentation language. <ListBox x:Name="MyListBox" ItemsSource="{Binding MyData, Mode=TwoWay}" BorderThickness="0"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding ElementName=Name,Path=Text}" /> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> EDIT: Option 1 <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding Id}" /> This option gives me just the Id, which is useful in many situations. EDIT: Option 2 <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding}" /> This option gives me the full model, which is even useful for my particular situation.

    Read the article

  • How do you pass a BitmapImage from a background thread to the UI thread in WPF?

    - by DanM
    I have a background thread that generates a series of BitmapImage objects. Each time the background thread finishes generating a bitmap, I would like to show this bitmap to the user. The problem is figuring out how to pass the BitmapImage from the background thread to the UI thread. This is an MVVM project, so my view has an Image element: <Image Source="{Binding GeneratedImage}" /> My view-model has a property GeneratedImage: private BitmapImage _generatedImage; public BitmapImage GeneratedImage { get { return _generatedImage; } set { if (value == _generatedImage) return; _generatedImage= value; RaisePropertyChanged("GeneratedImage"); } } My view-model also has the code that creates the background thread: public void InitiateGenerateImages(List<Coordinate> coordinates) { ThreadStart generatorThreadStarter = delegate { GenerateImages(coordinates); }; var generatorThread = new Thread(generatorThreadStarter); generatorThread.ApartmentState = ApartmentState.STA; generatorThread.IsBackground = true; generatorThread.Start(); } private void GenerateImages(List<Coordinate> coordinates) { foreach (var coordinate in coordinates) { var backgroundThreadImage = GenerateImage(coordinate); // I'm stuck here...how do I pass this to the UI thread? } } I'd like to somehow pass backgroundThreadImage to the UI thread, where it will become uiThreadImage, then set GeneratedImage = uiThreadImage so the view can update. I've looked at some examples dealing with the WPF Dispatcher, but I can't seem to come up with an example that addresses this issue. Please advise.

    Read the article

  • How to tell which dataform button ended edit when using EventToCommand

    - by Rodd
    I'm new to SilverLight and Mvvm-Light. I have a DataForm on my view that displays/edits a SelectedPerson property (a Person object) of my view model. I want to execute a command on my viewmodel when the user clicks the Save button but don't want to take action if the user clicks cancel. I added the following to my ViewModel: public RelayCommand PersonEditEnded {get; set;} ... public void Initialize() { PersonEditEnded = new RelayCommand(DoSomething); ... } public void DoSomething() { } I added the following to my View: <toolkit:DataForm x:Name="PersonForm" ... CurrentItem="{Binding SelectedPerson, Mode=TwoWay}"> <i:Interaction.Triggers> <i:EventTrigger EventName="EditEnded"> <gs:EventToCommand Command="{Binding PersonEditEnded, Mode=OneWay}"/> </i:EventTrigger> </i:Interaction.Triggers> </toolkit:DataForm> This works and the DoSomething method is being called when the user presses Submit. However, DoSomething is also called when user presses Cancel. Is there a way to know which button was pressed or to supress the call when Cancel is pressed? Thanks for whatever help you can offer!

    Read the article

  • Validation L2S question

    - by user158020
    This may be a bit winded because I am new to wpf. I have created a partial class for an entity in my L2S class that is primarily used for validation. It implements the onchanging and onvalidate methods. I am trying to use the MVVM pattern, and in a window/view I have set the datacontext in the xaml: <Window.DataContext> <vm:StartViewModel /> </Window.DataContext> when a user leaves a required field in the view blank, the onchanging event of the partial class is fired when I close the form, not when I save the data. So, if a user leaves the textbox blank, the old value is retained and the onchaging method is fired, but I have no idea how to alert the user of the resulting error. here is my onchanging code in the partial class: partial void Ondocument_titleChanging(string value) { if (value.Length == 0) throw new Exception("Document title is required."); if (value.Length > 256) throw new Exception("Document title cannot be longer than 256 characters."); } throwing an exception doesn't notify the user of the error. it just allows the form to close and rejects the changes to the textbox. hope this makes sense... edit: this example was taken from Scott Guthries article here: http://aspalliance.com/1427_LINQ_to_SQL_Part_5__Binding_UI_using_the_ASPLinqDataSource_Control.5

    Read the article

  • Set form MinWidth and MinHeight based on child property

    - by Jon Mitchell
    I'm writing an application in WPF using the MVVM pattern. In my application I've got an IPopupWindowService which I use to create a popup dialog window. So to show a ViewModel in a popup window you'd do something like this: var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); var popupService = container.Resolve<IPopupWindowService>(); var myViewModel = container.Resolve<IMyViewModel>(); popupService.Show((ViewModelBase)myViewModel); This is all well and good. What I want to do is be able to set the MinHeight and MinWidth on the View bound to myViewModel and have the popup window use those settings so that a user cannot make the window smaller than its contents will allow. At the moment when the user shrinks the window the contents stops resizing but the window doesn't. EDIT: I map my Views to my ViewModels in ResourceDictionarys like so: <DataTemplate DataType="{x:Type ViewModels:MyViewModel}"> <Views:MyView /> </DataTemplate> And my popup view looks like this: <Window x:Class="TheCompany.Cubit.Shell.Views.PopupWindowView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterOwner"> <DockPanel x:Name="panelContent"> <StackPanel HorizontalAlignment="Right" DockPanel.Dock="Bottom" Orientation="Horizontal" Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=ButtonPanelVisibility}"> <Button Width="75" IsDefault="True" x:Uid="ViewDialog_AcceptButton" Click="OnAcceptButtonClick" Margin="4">OK</Button> <Button Width="75" IsCancel="True" x:Uid="ViewDialog_CancelButton" Click="OnCancelButtonClick" Margin="0,4,4,4">Cancel</Button> </StackPanel> <ContentPresenter Content="{Binding}" /> </DockPanel>

    Read the article

  • How can I change the visibility of elements inside a DataTemplate when a row is selected in a Silver

    - by miketrash
    I'm using the MVVM pattern. I've bound my items and I want to only show the edit button when a row is selected in the datagrid. It appears to be possible with triggers in WPF but we don't have triggers in Silverlight. I tried a TemplatedParent binding but I'm not sure what the TemplatedParent is in this case. We don't have RelativeSource ancestor in Silverlight either. At this point I'm going to look at a solution using the code behind... <data:DataGrid.Columns> <data:DataGridTemplateColumn IsReadOnly="True" Header="Name" Width="300"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock x:Name="textBlock" Text="{Binding Name, Mode=OneWay}" VerticalAlignment="Center" Margin="4,4,0,4"/> <Button Margin="1,1,4,1" HorizontalAlignment="Right" VerticalAlignment="Center" Padding="7,4" Content="Edit" /> </Grid> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns>

    Read the article

  • Regarding the ViewModel

    - by mizipzor
    Im struggling to understand the ViewModel part of the MVVM pattern. My current approach is to have a class, with no logic whatsoever (important), except that it implements INotifyPropertyChanged. The class is just a collection of properties, a struct if you like, describing an as small part of the data as possible. I consider this my Model. Most of the WPF code I write are settings dialogs that configure said Model. The code-behind of the dialog exposes a property which returns an instance of the Model. In the XAML code I bind to subproperties of that property, thereby binding directly to the Model's properties. Which works quite well since it implements the INotifyPropertyChanged. I consider this settings dialog the View. However, I havent really been able to figure out what in all this is the ViewModel. The articles Ive read suggests that the ViewModel should tie the View and the Model together, providing the logic the Model lacks but is still to complex to go directly into the View. Is this correct? Would, in my example, the code-behind of the settings dialog be considered the ViewModel? I just feel a bit lost and would like my peers to debunk some of my assumptions. Am I completely off track here?

    Read the article

  • Avoiding mass propagation of properties and events for exposure to ViewModels.

    - by firoso
    I have an MVVM application I am developing that is to the point where I'm ready to start putting together a user interface (my client code is largely functional) I'm now running into the issue that I'm trying to get my application data to where I need it so that it can be consumed by the view model and then bound to the view. Unfortunately, it seems that I've either got a few structural oversights, or I'm just going to have to face the reality that I need to be propogating events and raising excessive amounts of errors to notify view models that thier properties have changed. Let me go into some examples of my issue: I have a class "Unit" contained in a class "Test", contained in a class "Session" contained in a class "TestManager" which is contained in "TestDataModel" which is utilized by "TestViewModel" which is databound to by my "TestView" .... WHOA. Now, consider that Unit (the bottom of the heiarchy) has a property called "Results" that is updated periodically, I want to expose that to my viewmodel and then databind it to my view, trouble is, the only way I can really think to do this is to perpetuate events WAY up a chain that say "I've been updated!" and then request the new value... This seems like an aweful way to do this. Alternatively, I could register a static event and raise it, and have the appropriate "Unit view model" grab the event and request the update. This SEEMS better... but... static events? Is that a taboo idea? Also, having an expression like: TestDataModel.TestManager.Session.Test.Unit.Results[i] Seems REALLY gross to have on a View Model. I know this all reeks of a bad design issue, but I can't figure out what I did wrong? Should I be using more singleton/container controlled lifetimes type objects? Register object instances with static helper containers? Obviously these are hard questions to answer without being intimate with the existing structure, but if you've run into situations like this, what did you do to refactor? Should I just live with this, add mass events, and propogate them?

    Read the article

  • Focus-dependent text change for TextBoxes in WPF

    - by Simon
    Hey there. I'm writing an application in WPF using the MVVM-pattern and will really often use TextBoxes. I don't want to use labels for the user to know user what the text box is for, i.e. I don't want something like this: <TextBlock> Name: </TextBlock> <TextBox /> Instead, I would like the TextBox to contain its own label. Statically, you would express it like this: <TextBox>Name</TextBox> If the cursor is displayed in the textbox, i.e. the TextBox gains focus, I want the description text to disappear. If the TextBox is left empty and it loses the focus, the description text should be shown again. It's similar to the search textbox of StackOverflow or the one of Firefox. (please tell me if your not sure what I mean). One TextBox's label may change at runtime, dependending on e.g. a ComboBox's selected element or a value in my ViewModel. (It's like in Firefox's search TextBox, if you select google from the search engins' menu, the TextBox's label changes to "Google", if you select "Yahoo" its set to "Yahoo"). Thus I want to be able to bind the label's content. Consider that I may already have a Binding on the Text-Property of the TextBox. How can implement such a behaviour and make it reusable for any of my TextBox's? Code is welcome but not needed; a description of what to do is enough. Thank you in advance.

    Read the article

  • Grouping Categorized Data In WPF.

    - by VoidDweller
    Here is what I am trying to do. Dynamic Category: Columns can be 0 or more. Must contain 1 or more Type Columns. Will only be displayed if any row contains Type Column data associated with it. Data Rows: Will be added Asynchronously. Will be grouped by a Common Category column. Will add a Dynamic Category if it does not yet exist. Will add a Type Column if it does not yet exist within its appropriate Dynamic Category. Platform Info: WPF .Net 3.5 sp1 C# MVVM I have a few partially functional prototypes, but each has it's own major set of problems. Can any of you give me some guidance on this? Envision this nicely styled. :-) -------------------------------------------------------------------------- |[ Common Category ]|[ Dynamic Category 0 ]|[ Dynamic Category N ]| -------------------------------------------------------------------------- |[Header 1]|[Header 2]|[ Type 0 ]|[ Type N ]|[ Type 0 ]|[ Type N ]| -------------------------------------------------------------------------- |[Data 2 Group] | -------------------------------------------------------------------------- | Data A | Data 2 || Null | Data 1 || Data 0 | Data 1 || | Data B | Data 2 || Data 0 | Null || Data 0 | Data 1 || -------------------------------------------------------------------------- |[Data 1 Group] | -------------------------------------------------------------------------- | Data C | Data 1 || Null | Data 1 || Data 0 | Data 1 || | Data D | Data 1 || Null | Null || Data 0 | Null || -------------------------------------------------------------------------- Edit: Sorting and Paging is not necessary. I have looked at nested ListViews and DataGrids, dynamically building a Grid. Dynamically building a Grid and leveraging the SharedSizeGroup property seems the most promising strategy, but I am concerned about performance. Would a better approach be to consider this a dynamic report? If so, what should I be looking at? Thanks for your help.

    Read the article

  • WP7: Why does a ListBox.ItemsPanel break my ElementName data binding?

    - by iguanaNet
    I have a Windows Phone 7 ListBox that binds to a list of integers. I am using the default MVVM Light template, so there is a ViewModel class that contains data and a simple RelayCommand. Here is the ListBox: <ListBox ItemsSource="{Binding MyData}"> <ListBox.ItemTemplate> <DataTemplate> <Button Content="{Binding}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding ElementName=ContentGrid, Path=DataContext.TestCommand}" CommandParameter="{Binding}" /> </i:EventTrigger> </i:Interaction.Triggers> </Button> </DataTemplate> </ListBox.ItemTemplate> </ListBox> This displays a vertical list of integers inside buttons. If you click any of them, the following command code executes and shows a pop-up: new RelayCommand<int>(i => MessageBox.Show("Test" + i)); However, if I simply add the following XAML to change to a horizontal list, the databinding fails. Nothing happens when you click the button and no error messages are written to the Output window. <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" /> </ItemsPanelTemplate> </ListBox.ItemsPanel> I have tried some other types of binding for the EventToCommand. For example, specifying my ViewModel as a static resource. It works, but is less ideal than the example above. Why does that ItemsPanel break the databinding?

    Read the article

  • Choosing right control for list of items

    - by prostynick
    I am new to WPF and MVVM. In my ViewModel I have collection of items, for example: class Item { string Title {get; set;} string Description {get; set;} } I would like to create a view, so at the beginning I would have: Title1 Title2 Title3 If user click on one of title it will expand to show description, eg: Title1 Description1 Title2 Title3 If user click on other title, there will be two expanded items: Title1 Description1 Title2 Description2 Title3 This is probably very similar to Expander control and maybe I could use it, but I am doing it other way, to learn something new. What control should I use for this purpose? Should that be ItemsControl or maybe ListBox? I imagine, that if I use ItemsControl, I should probably extend my Item class to have something like bool IsExpanded and bind UI item visibility to that value. But maybe I could use ListBox and somehow bind UI item visibility to... Yeah, to what? :) How could I do such a simple thing?

    Read the article

  • Bind an Incode DataTemplate in WPF

    - by Mike Bynum
    I have a WPF Application which is using MVVM. I know that there ways of doing this in XAML but I am working on a plugin architecture and came up with a solution where a plugin exposes it's viewmodel to my plugin host's viewmodel and it's datatemplate. I want to leave the lifetime management of the plugin view up to WPF. I have tried having the plugins expose a UserControl but ran into issues when WPF decided to dispose of my UserControl so I would not reattach it without weird hacky work arounds. I am having issues getting some sort of binding working to where i can bind a control to the data and it's template to my data template. I have a ViewModel which looks something like: public class MyViewModel { public DataTemplate SelectedTemplate{ get; set;} public object SelectedViewModel {get; set;} } The selected template and viewmodel are determined somewhere else in the code but are irrelevant to my question. My question is how i can bind to a DataTemplate so that I know how to display the data shown in the SelectedViewModel. The DataTemplate is a DataTemplate created incode which respresents: <DataTemplate DataType="{x:Type vm:MyViewModel}"> <v:MyUserControl /> </DataTemplate> I have tried: <UserControl Template="{Binding Path=SelectedTemplate}" Content="{Binding Path=SelectedViewModel"} /> But UserControl expects a control template and not a data template.

    Read the article

  • WPF Calling a custom command on a custom control (from a viewmodel?)

    - by user190615
    I want to take a snap of the visual tree of a custom wpf control when the user clicks a button in a toolbar. The control is bound to a viewmodel. I have a BitmapSource dp in the custom control holding the snapped image which is bound to a property on my VM. The BitmapSource dp on the control is updated via a custom command on the control. I've tied the toolbar button's command to call the controls command which updates the BitmapSource. Now the problem is the end result I want is when the user clicks the button, the control updates its image and then the vm offers to save this image. I cant wrap my mind around an mvvm way of doing this. One inelegant solution is that control fires an event after the image is updated which is routed to the viewmodel as a command(command behavior) but then if i want to do something else with the image on some other button click, all the commands bound to the events will fire. All thoughts appreciated. EDIT The command on the control is a RoutedCommand and the commands in my vm are Prism delegate commands.

    Read the article

  • WPF: Setting DataContext of a UserControl with Binding not working in XAML

    - by Grant Crofton
    Hi, I'm trying to get my first WPF app working using MVVM, and I've hit a little binding problem. The setup is that I have a view & viewModel which holds User details (the parent), and to try and keep things simple I've put a section of that view into a separate view & viewModel (the child). The child view is defined as a UserControl. The issue I'm having is how to set the DataContext of the child view (the UserControl). My parent ViewModel has a property which exposes the child ViewModel, like so: class ParentViewModel: INotifyPropertyChanged { public ChildViewModel childViewModel { get; set; } //... } In the XAML for my parent view (which has it's DataContext set to the ParentViewModel), I try to set the DataContext of the child view as follows: <views:ChildView x:Name="ChildView" DataContext="{Binding childViewModel}"/> However, this doesn't work. The DataContext of the child view is set to the same DataContext as the parent view (i.e. the ParentViewModel), as if I wasn't setting it at all. I also tried setting the DataContext in the child view itself, which also doesn't work: <UserControl x:Class="DietRecorder.Client.View.ChildView" DataContext="childViewModel" I have found a couple of ways around this. In the child view, I can bind everything by including the ChildViewModel in the path: <SomeControl Visibility="{Binding Path=childViewModel.IsVisible}"> but I don't want the child view to have this level of awareness of the hierarchy. Setting the DataContext in code also works - however, I have to do this after showing the parent view, otherwise the DataContext just gets overwritten when I call Show(): parentView.Show(); parentView.ChildView.DataContext = parentViewModel.childViewModel; This code also makes me feel uneasy, what with the LOD violation and all. It's just the DataContext that seems to be the problem - I can bind other things in the child, for example I tried binding the FontSize to an int property just to test it: <views:ChildView x:Name="ChildView" FontSize="{Binding Path=someVal}"/> And that works fine. But I'm sure binding the DataContext should work - I've seen similar examples of this kind of thing. Have I missed something obvious here? Is there a reason this won't work? Is there a spelling mistake somewhere? (I renamed things for your benefit so you won't be able to help me there anyway). Any thoughts welcome. Thanks, Grant

    Read the article

  • Defining InputBindings within a Style

    - by Brent
    I'm creating a WPF app using the MVVM design pattern, and I'm trying to extend the TabItem control so that it closes the tab when the user clicks the middle mouse button. I'm trying to achieve this using InputBindings, and it works very well until I try to define it within a style. I've learned that you cannot add InputBindings to a style unless you attach it using a DependencyProperty. So I followed this similar post here... and it works... almost. I can close one tab using the middle mouse button, but it won't work on any of the other tabs (all of the tabs are added at runtime and inherit the same style). So I need some help. Why would this only be working the first time, and not after? Obviously I could create a custom control that inherits from a TabItem and make it work, but I'd like to figure this out as I can see this being expanded in my projects. I'm no expert on DependencyProperties, so please help me out. Thanks! Style: <Style TargetType="{x:Type TabItem}"> <Setter Property="w:Attach.InputBindings"> <Setter.Value> <InputBindingCollection> <MouseBinding MouseAction="MiddleClick" Command="{Binding CloseCommand}"/> </InputBindingCollection> </Setter.Value> </Setter> ... </Style> Class public class Attach { public static readonly DependencyProperty InputBindingsProperty = DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(Attach), new FrameworkPropertyMetadata(new InputBindingCollection(), (sender, e) => { var element = sender as UIElement; if (element == null) return; element.InputBindings.Clear(); element.InputBindings.AddRange((InputBindingCollection)e.NewValue); })); public static InputBindingCollection GetInputBindings(UIElement element) { return (InputBindingCollection)element.GetValue(InputBindingsProperty); } public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings) { element.SetValue(InputBindingsProperty, inputBindings); } }

    Read the article

  • M-V-VM, isn't the Model leaking into the View?

    - by BFree
    The point of M-V-VM as we all know is about speraration of concerns. In patterns like MVVM, MVC or MVP, the main purpose is to decouple the View from the Data thereby building more flexible components. I'll demonstrate first a very common scenario found in many WPF apps, and then I'll make my point: Say we have some StockQuote application that streams a bunch of quotes and displays them on screen. Typically, you'd have this: StockQuote.cs : (Model) public class StockQuote { public string Symbol { get; set; } public double Price { get; set; } } StockQuoteViewModel.cs : (ViewModel) public class StockQuoteViewModel { private ObservableCollection<StockQuote> _quotes = new ObservableCollection<StockQuote>(); public ObservableCollection<StockQuote> Quotes { get { return _quotes; } } } StockQuoteView.xaml (View) <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="300"> <Window.DataContext> <local:StockQuoteViewModel/> </Window.DataContext> <Window.Resources> <DataTemplate x:Key="listBoxDateTemplate"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Symbol}"/> <TextBlock Text="{Binding Price}"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemTemplate="{StaticResource listBoxDateTemplate}" ItemsSource="{Binding Quotes}"/> </Grid> </Window> And then you'd have some kind of service that would feed the ObservableCollection with new StockQuotes. My question is this: In this type of scenario, the StockQuote is considered the Model, and we're exposing that to the View through the ViewModel's ObservableCollection. Which basically means, our View has knowledge of the Model. Doesn't that violate the whole paradigm of M-V-VM? Or am I missing something here....?

    Read the article

  • I know I'm doing something wrong with RaiseCanExecuteChanged and CanExecute

    - by Cowman
    Well after fiddling with MVVM light to get my button to enable and disable when I want it to... I sort of mashed things together until it worked. However, I just know I'm doing something wrong here. I have RaiseCanExecuteChanged and CanExecute in the same area being called. Surely this is not how it's done? Here's my xaml <Button Margin="10, 25, 10, 25" VerticalAlignment="Center" HorizontalAlignment="Center" Width="50" Height="50" Grid.Column="1" Grid.Row="3" Content="Host"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <mvvmLight:EventToCommand Command="{Binding HostChat}" MustToggleIsEnabled="True" /> </i:EventTrigger> </i:Interaction.Triggers> </Button> And here's my code public override void InitializeViewAndViewModel() { view = UnityContainer.Resolve<LoginPromptView>(); viewModel = UnityContainer.Resolve<LoginPromptViewModel>(); view.DataContext = viewModel; InjectViewIntoRegion(RegionNames.PopUpRegion, view, true); viewModel.HostChat = new DelegateCommand(ExecuteHostChat, CanHostChat); viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ViewModelPropertyChanged); } void ViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Name" || e.PropertyName == "Port" || e.PropertyName == "Address") { (viewModel.HostChat as DelegateCommand).RaiseCanExecuteChanged(); (viewModel.HostChat as DelegateCommand).CanExecute(); } } public void ExecuteHostChat() { } public bool CanHostChat() { if (String.IsNullOrEmpty(viewModel.Address) || String.IsNullOrEmpty(viewModel.Port) || String.IsNullOrEmpty(viewModel.Name)) { return false; } else return true; } See how these two are together? Surely that can't be right. I mean... it WORKS for me... but something seems wrong about it. Shouldn't RaiseCanExecuteChanged call CanExecute? It doesn't... and so if I don't have that CanExecute in there, my control never toggles its IsEnabled like I need it to. (viewModel.HostChat as DelegateCommand).RaiseCanExecuteChanged(); (viewModel.HostChat as DelegateCommand).CanExecute();

    Read the article

  • Rendering a WPF Network Map/Graph layout - Manual? PathListBox? Something Else?

    - by Ben Von Handorf
    I'm writing code to present the user with a simplified network map. At any given time, the map is focused on a specific item... say a router or a server. Based on the focused item, other network entities are grouped into sets (i.e. subnets or domains) and then rendered around the focused item. Lines would represent connections and groups would be visually grouped inside a rectangle or ellipse. Panning and zooming are required features. An item can be selected to display more information in a "properties" style window. An item could also be double-clicked to re-focus the entire network map on that item. At that point, the entire map would be re-calculated. I am using MVVM without any framework, as of yet. Assume the logic for grouping items and determining what should be shown or not is all in place. I'm looking for the best way to approach the UI layout. So far, I'm aware of the following options: Use a canvas for layout (inside a ScrollViewer to handle the panning). Have my ViewModel make use of a Layout Manager type of class, which would handle assigning all the layout properties (Top, Left, etc.). Bind my set of display items to an ItemsControl and use Data Templates to handle the actual rendering. The drawbacks with this approach: Highly manual layout on my part. Lots of calculation. I have to handle item selection manually. Computation of connecting lines is manual. The Pros of this approach: I can draw additional lines between child subnets as appropriate (manually). Additional LayoutManagers could be added later to render the display differently. This could probably be wrapped up into some sort of a GraphLayout control to be re-used. Present the focused item at the center of the display and then use a PathListBox for layout of the additional items. Have my ViewModel expose a simple list of things to be drawn and bind them to the PathListBox. Override the ListBoxItem Template to also create a line geometry from the borders of the focused item (tricky) to the bound item. Use DataTemplates to handle the case where the item being bound is a subnet, in which case we would use another PathListBox in the template to display items inside the subnet. The drawbacks with this approach: Selected Item synchronization across multiple `PathListBox`es. Only one item on the whole graph can be selected at a time, but each child PathListBox maintains its own selection. Also, subnets cannot be selected, but would be selectable without additional work. Drawing the connecting lines is going to be a bit of trickery in the ListBoxItem template, since I need to know the correct side of the focused item to connect to. The pros of this approach: I get to stay out of the layout business, more. I'm looking for any advice or thoughts from others who have encountered similar issues or who have more WPF experience than I. I'm using WPF 4, so any new tricks are legal and encouraged.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >