Search Results

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

Page 25/50 | < Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >

  • how to parametrize an import in a View?

    - by Gianluca Colucci
    Hello everybody, I am looking for some help and I hope that some good soul out there will be able to give me a hint :) In the app I am building, I have a View. When an instance of this View gets created, it "imports" (MEF) the corresponding ViewModel. Here some code: public partial class ContractEditorView : Window { public ContractEditorView () { InitializeComponent(); CompositionInitializer.SatisfyImports(this); } [Import(ViewModelTypes.ContractEditorViewModel)] public object ViewModel { set { DataContext = value; } } } and here is the export for the ViewModel: [PartCreationPolicy(CreationPolicy.NonShared)] [Export(ViewModelTypes.ContractEditorViewModel)] public class ContractEditorViewModel: ViewModelBase { public ContractEditorViewModel() { _contract = new Models.Contract(); } } Now, this works if I want to open a new window to create a new contract... But it does not if I want to use the same window to edit an existing contract... In other words, I would like to add a second construct both in the View and in the ViewModel: the original constructor would accept no parameters and therefore it would create a new contract; the new construct - the one I'd like to add - I'd like to pass an ID so that I can load a given entity... What I don't understand is how to pass this ID to the ViewModel import... Thanks in advance, Cheers, Gianluca.

    Read the article

  • using EventToCommand & PassEventArgsToCommand :: how to get sender, or better metaphor?

    - by JoeBrockhaus
    The point of what I'm doing is that there are a lot of things that need to happen in the viewmodel, but when the view has been loaded, not on constructor. I could wire up event handlers and send messages, but that just seems kinda sloppy to me. I'm implementing a base view and base viewmodel where this logic is contained so all my views get it by default, hopefully. Perhaps I can't even get what I'm wanting: the sender. I just figured this is what RoutedEventArgs.OriginalSource was supposed to be? [Edit] In the meantime, I've hooked up an EventHandler in the xaml.cs, and sure enough, OriginalSource is null there as well. So I guess really I need to know if it's possible to get a reference to the view/sender in the Command as well? [/Edit] My implementation requires that a helper class to my viewmodels which is responsible for creating 'windows' knows of the 'host' control that all the windows get added to. i'm open to suggestions for accomplishing this outside the scope of using eventtocommand. :) (the code for Unloaded is the same) #region ViewLoadedCommand private RelayCommand<RoutedEventArgs> _viewLoadedCommand = null; /// <summary> /// Command to handle the control's Loaded event. /// </summary> public RelayCommand<RoutedEventArgs> ViewLoadedCommand { get { // lazy-instantiate the RelayCommand on first usage if (_viewLoadedCommand == null) { _viewLoadedCommand = new RelayCommand<RoutedEventArgs>( e => this.OnViewLoadedCommand(e)); } return _viewLoadedCommand; } } #endregion ViewLoadedCommand #region View EventHandlers protected virtual void OnViewLoadedCommand(RoutedEventArgs e) { EventHandler handler = ViewLoaded; if (handler != null) { handler(this, e); } } #endregion

    Read the article

  • WPF View/ViewModels using Generics- how?

    - by Investor5555
    New to WPF, so please bear with me... Suppose I have 2 tables in SQL Thing OtherThing Both have the exact same fields: ID (int) Name (string) Description (string) IsActive (bit/bool) DateModified (DateTime) So, I want to create one Model (not two) and do something like this: BaseModel<T>() { public int ID {get;set;} ... } etc. (of course, using the INotifyPropertyChanged, just trying to keep the code simple). I want to be able to create a BaseView and BaseViewModel that would work with whatever model conforms to the Thing/OtherThing. I am really at a loss as to what to do here to make this generic, so I don't have to have a ThingView/ThingViewModel and a OtherThingView/OtherThingViewModel... It seems that this should be simple, but I cannot seem to figure it out. Does anyone have a code example where they could interchange various items from a dropdown list using one view, one ViewModel, and one base datamodel (and switching out the type from a dropdown)? For example, a combobox has 3 identical table structures for Thing OtherThing SomeThing and on selection changed, I want to pull the data from whatever table was selected, to be able to do standard CRUD operations on any of these 3 tables, without having to create concrete classes for each view/viewmodel.

    Read the article

  • Can I remove duplicating events in EventAggregator?

    - by Mcad001
    Hi, I have a quite simple scenario that I cannot get to work correctly. I have 2 views, CarView and CarWindowView (childwindow) with corresponding ViewModels. In my CarView I have an EditButton that that opens CarWindowView (childwindow) where I can edit the Car object fields. My problem is that the DisplayModule method in my CarWindowView ViewModel is getting called too many times...When I push the edit button first time its getting called once, the second time its getting called twince, the third time its getting called 3 times and so fort... ! CarView ViewModel constructor: Public Sub New(ByVal eventAggregator As IEventAggregator, ByVal con As IUnityContainer, ByVal mgr As ICarManager, ByVal CarService As ICarService) _Container = con _CarManager = mgr _EventAggregator = eventAggregator 'Create the DelegateCommands NewBtnClick = New DelegateCommand(Of Object)(AddressOf HandleNewCarBtnClick) EditBtnClick = New DelegateCommand(Of Object)(AddressOf HandleEditCarBtnClick) End Sub CarView ViewModel HandleEditCarBtnClick method: Private Sub HandleEditCarBtnClick() Dim view = New CarWindowView Dim viewModel = _Container.Resolve(Of CarWindowViewModel)() viewModel.CurrentDomainContext = DomainContext viewModel.CurrentItem = CurrentItem viewModel.IsEnabled = False view.ApplyModel(viewModel) view.Show() _EventAggregator.GetEvent(Of CarCollectionEvent)().Publish(EditObject) End Sub CarWindowView ViewModel constructor: Public Sub New(ByVal eventAggregator As IEventAggregator, ByVal con As IUnityContainer, ByVal mgr As ICarManager, ByVal CarService As ICarService) _Container = con _CarManager = mgr _EventAggregator = eventAggregator _EventAggregator.GetEvent(Of CarCollectionEvent).Subscribe(AddressOf DisplayModule) End Sub CarWindowView ViewModel DisplayModule method (this is the method getting called too many times): Public Sub DisplayModule(ByVal param As String) If param = EditObject Then IsInEditMode = True ' Logic removed for display reasons here. This logic breaks because it's called too many times. End If End Sub So, I cannot understand how I can only have the EventAggregator to store just the one single click, and not all my click on the Edit button. Sorry if this is not to well explained! Help appreciated!!

    Read the article

  • How do I apply a ViewModel to the UserControl inside of a Page?

    - by Mike
    Doing something like this: <DataTemplate DataType="{x:Type vm:AllCustomersViewModel}"> <vw:AllCustomersView /> </DataTemplate> works in a ResourceDictionary for when I want to apply a ViewModel to a UserControl as root, but how do I the same thing when I have a UserControl inside of a Page? Would I create a ResourceDictionary for all my Pages then at the top of each Page do something like: <Page.Resources> <ResourceDictionary Source="../MainWindowResources.xaml"/> </Page.Resources> Any help is greatly appreciated, thanks!

    Read the article

  • Hierarchy as grid

    - by seesharp
    I have hierarchy: public class Parameter { public string Name { get; set; } public Value Value { get; set; } } public abstract class Value { } public class StringValue : Value { public string Str { get; set; } } public class ComplexValue : Value { public ComplexValue() { Parameters = new List<Parameter>(); } public List<Parameter> Parameters { get; set; } } /// Contains ComplexValue public class ComplexParameter : Parameter { } And XAML with templates <Window.Resources> <DataTemplate DataType="{x:Type pc:Parameter}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Label Grid.Column="0" Content="{Binding Name}"/> <ContentPresenter Grid.Column="1" Content="{Binding Value}"/> </Grid> </DataTemplate> <DataTemplate DataType="{x:Type pc:ComplexParameter}"> <StackPanel> <Label Content="{Binding Name}"/> <ContentControl Margin="18,0,0,0" Content="{Binding Value}"/> </StackPanel> </DataTemplate> <DataTemplate DataType="{x:Type pc:ComplexValue}"> <ItemsControl ItemsSource="{Binding Parameters}"/> </DataTemplate> <DataTemplate DataType="{x:Type pc:StringValue}"> <TextBox Text="{Binding Str}"/> </DataTemplate> </Window.Resources> This look like: Param1 -Control---- Param2 -Control---- Complex1 Sub Param1 -Control- Sub Param2 -Control- Or image here: freeimagehosting.net/uploads/9d438f52e7.png Question How to do indent only in left column (parameter names). Something like this: Param1 -Control---- Param2 -Control---- Complex1 Sub Param1 -Control---- Sub Param2 -Control---- Or image here: freeimagehosting.net/uploads/4ab3045b75.png

    Read the article

  • Silverlight Data Binding for Collection in Stack Panel

    - by Blake Blackwell
    I'm new to Silverlight, so I don't have a complete grasp of all the controls at my disposal. What I would like to do is use databinding and a view model to maintain a collection of items. Here is some mock code for what I'd like to do: Model public class MyItem { public string DisplayText { get; set; } public bool Enabled { get; set; } } ViewModel public class MyViewModel : INotifyPropertyChanged { private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>(); public ObservableCollection<MyItem> MyItems { get { return _myItems; } set { _myItems = value NotifyPropertyChanged(this, "MyItems"); } } } View <Grid x:Name="LayoutRoot" Background="White"> <StackPanel ItemsSource="{Binding MyItems}"> <StackPanel Orientation="Horizontal"> <CheckBox "{Binding Enabled, Mode=TwoWay}"></CheckBox> <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" /> </StackPanel> </StackPanel> </Grid> So my end goal would be that every time I add another MyItem to the MyItems collection it would create a new StackPanel with checkbox and textblock. I don't have to use a stack panel but just thought I'd use that for this sample.

    Read the article

  • Binding a Value from a View-Model to the View-Model of a child User Control in Silverlight?

    - by andrej351
    Hi there, So i have a UserControl for one of my Views and have another 'child' UserControl inside that. The outer 'parent' UserControl has a Collection on its View-Model and a Grid control on it to display a list of Items. I want to place another UserControl inside this UserControl to display a form representing the details of one Item. The outer / parent UserControl's View-Model already has a property on it to hold the currently selected Item and i would like to bind this to a DependancyProperty on the inner / child UserControl. I would then like to bind that DependancyProperty to a property on the child UserControl's View-Model. I can then set the DependancyProperty once in XAML with a binding expression and have the child UserControl do all its work in its View-Model like it should. The code i have looks like this.. Parent UserControl: <UserControl x:Class="ItemsListView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel}"> <!-- Grid Control here... --> <ItemDetailsView Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel.SelectedItem}" /> </UserControl> Child UserControl: <UserControl x:Class="ItemDetailsView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel}" ItemDetailsView.Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel.Item, Mode=TwoWay}"> <!-- Form controls here... --> </UserControl> The selected Item is bound to the DependancyProperty fine. However from the DependancyProperty to the child View-Model does not. I've used this sort of apporach in a WPF app without problems. It appears to be a situation where there are two concurrent bindings which need to work but with the same target for two sources. Why won't the second (in the child UserControl) binding work?? Is there a way to acheive the behaviour I'm after?? Cheers.

    Read the article

  • How can I display the clicked products by user on a list in another view?

    - by Avar
    I am using MVC3 Viewmodel pattern with Entity Framework on my webbapplication. My Index View is list of products with image, price and description and etc. Products with the information I mentioned above is in div boxes with a button that says "buy". I will be working with 2 views one that is the Index View that will display all the products and the other view that will display the products that got clicked by the buy button. What I am trying to achieve is when a user click on buy button the products should get stored in the other view that is cart view and be displayed. I have problems on how to begin the coding for that part. The index View with products is done and now its the buy button function left to do but I have no idea how to start. This is my IndexController: private readonly HomeRepository repository = new HomeRepository(); public ActionResult Index() { var Productlist = repository.GetAllProducts(); var model = new HomeIndexViewModel() { Productlist = new List<ProductsViewModel>() }; foreach (var Product in Productlist) { FillProductToModel(model, Product); } return View(model); } private void FillProductToModel(HomeIndexViewModel model, ProductImages productimage) { var productViewModel = new ProductsViewModel { Description = productimage.Products.Description, ProductId = productimage.Products.Id, price = productimage.Products.Price, Name = productimage.Products.Name, Image = productimage.ImageUrl, }; model.Productlist.Add(productViewModel); } In my ActionResult Index I am using my repository to get the products and then I am binding the data from the products to my ViewModel so I can use the ViewModel inside my view. Thats how I am displaying all the products in my View. This is my Index View: @model Avan.ViewModels.HomeIndexViewModel @foreach (var item in Model.Productlist) { <div id="productholder@(item.ProductId)" class="productholder"> <img src="@Html.DisplayFor(modelItem => item.Image)" alt="" /> <div class="productinfo"> <h2>@Html.DisplayFor(modelItem => item.Name)</h2> <p>@Html.DisplayFor(modelItem => item.Description)</p> @Html.Hidden("ProductId", item.ProductId, new { @id = "ProductId" }) </div> <div class="productprice"> <h2>@Html.DisplayFor(modelItem => item.price)</h2> <input type="button" value="Läs mer" class="button" id="button@(item.ProductId)"> @Html.ActionLink("x", "Cart", new { id = item.ProductId }) // <- temp its going to be a button </div> </div> } Since I can get the product ID per product I can use the ID in my controller to get the data from the database. But I still I have no idea how I can do that so when somebody click on the buy button I store the ID where? and how do I use it so I can achieve what I want to do? Right now I have been trying to do following thing in my IndexController: public ActionResult cart(int id) { var SelectedProducts = repository.GetProductByID(id); return View(); } What I did here is that I get the product by the id. So when someone press on the temp "x" Actionlink I will recieve the product. All I know is that something like that is needed to achieve what im trying to do but after that I have no idea what to do and in what kind of structure I should do it. Any kind of help is appreciated alot! Short Scenario: looking at the Index I see 5 products, I choose to buy 3 products so I click on three "Buy" buttons. Now I click on the "Cart" that is located on the nav menu. New View pops up and I see the three products that I clicked to buy.

    Read the article

  • Reuse controls inside a usercontrol

    - by Lawrence A. Contreras
    I have a UserControl UserControl1 and a button inside the UserControl1. And I have a UserControl1ViewModel that has an ICommand property for the button. Using this command I need to call a method outside(from other VMs or VM of the MainWindow) the VM. What is the best practice for this?

    Read the article

  • How do you send in the LayoutRoot into a RelayCommand via a EventToCommand?

    - by user298145
    Grid example with the trigger: <Grid x:Name="LayoutRoot" DataContext="{Binding ProjectGrid, Source={StaticResource Locator}}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding LoadedCommand, Mode=OneWay}" PassEventArgsToCommand="True"/> </i:EventTrigger> </i:Interaction.Triggers> In my ViewModel I set the LoadedCommand like this: public RelayCommand<RoutedEventArgs> LoadedCommand {get;private set;} And in the ViewModel initializer I have this: public ProjectGridViewModel() { LoadedCommand = new RelayCommand<RoutedEventArgs>(e => { this.DoLoaded(e); } ); } Then, in my DoLoaded I'm trying to do this: Grid _projectGrid = null; public void DoLoaded(RoutedEventArgs e) { _projectGrid = e.OriginalSource as Grid; } You can see I'm trying to get rid of my Loaded="" in my Grid in my view, and do a RelayCommand instead. The issue is the OriginalSource brings back nothing. My loaded event is running nice this way, but I need to get the Grid in via the RoutedEventArgs it seems. I tried passing in the Grid in the EventCommand with CommandParameter="{Binding ElementName=LayoutRoot}", but this just crashes VS2010 when hitting F5 and running the project. Any ideas? Or a better way to do this? I had the Loaded event run in the views C# then call the ViewModel in the Views code-behind, but I'd like to do a nicer binding. Talking to the ViewMode in the Views code-behind feels like a hack.

    Read the article

  • Can't use Visual Studio 2008 Designer with MVVMLight V3 SP1

    - by mcauthorn
    I wish I knew what I did to cause this, but I cannot use the Visual Studio 2008 Designer at all with with MVVMLight templates. I receive a "Could not create an instance of type 'ViewModelLocator'. in any of my xaml pages. The application builds and runs fine but only the designer is broken. In the App.xaml is <Application x:Class="ExcelReportGenerator.App" 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" xmlns:vm="clr-namespace:ExcelReportGenerator.ViewModel" xmlns:res="clr-namespace:ExcelReportGenerator.Resources" Startup="Application_Startup" mc:Ignorable="d"> <Application.Resources> <!--Global View Model Locator--> <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> </Application.Resources> I even receive the error when I create a brand new MVVMLight application. The interesting thing is if I use an express version of VS2010 I can view, edit and work in designer just fine. As much as I would love to go to VS2010, I can't right now convince IT to make that move.

    Read the article

  • Value Object and View Model Property

    - by William
    I am working on a solution that used DDD for architecture. I have a property in my ViewModel which points to a ValueObject, the view model also implements INotifyPropertyChanged interface. The value of the ValueObject will change as a user enters data on the front end. The problem I am running into is the value object is suppose to be immutable. How can I work around this issue? Thank you in advance.

    Read the article

  • Passing parameters into ViewModels (Prism)

    - by vXtreme
    Hi I can't figure out how to pass parameters to my viewmodels from other views or viewmodels. For instance, I have a View called Customers. There is a grid inside, and if you double-click the grid, a new view is supposed to come up and allow you to edit that customer's data. But how will the View(Model) responsible for editing data know which customer it's supposed to open if I can't pass any parameters inside? EventAggregator is out of the question because I obviously can't create hundreds of eventargs, each for one view. And besides, it's a lousy solution. So far I was able to come up with: CustomerDataView custView = new CustomerDataView(customerId, currentContext); manager.Regions[RegionNames.Sidebar].AddAndActivate(custView); What do you think about this particular solution? Is this the way it's normally done? What I don't like about this is the fact that I lose out on automatic dependency injection by Unity.

    Read the article

  • Including partial views when applying the Mode-View-ViewModel design pattern

    - by Filip Ekberg
    Consider that I have an application that just handles Messages and Users I want my Window to have a common Menu and an area where the current View is displayed. I can only work with either Messages or Users so I cannot work simultaniously with both Views. Therefore I have the following Controls MessageView.xaml UserView.xaml Just to make it a bit easier, both the Message Model and the User Model looks like this: Name Description Now, I have the following three ViewModels: MainWindowViewModel UsersViewModel MessagesViewModel The UsersViewModel and the MessagesViewModel both just fetch an ObserverableCollection<T> of its regarding Model which is bound in the corresponding View like this: <DataGrid ItemSource="{Binding ModelCollection}" /> The MainWindowViewModel hooks up two different Commands that have implemented ICommand that looks something like the following: public class ShowMessagesCommand : ICommand { private ViewModelBase ViewModel { get; set; } public ShowMessagesCommand (ViewModelBase viewModel) { ViewModel = viewModel; } public void Execute(object parameter) { var viewModel = new ProductsViewModel(); ViewModel.PartialViewModel = new MessageView { DataContext = viewModel }; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; } And there is another one a like it that will show Users. Now this introduced ViewModelBase which only holds the following: public UIElement PartialViewModel { get { return (UIElement)GetValue(PartialViewModelProperty); } set { SetValue(PartialViewModelProperty, value); } } public static readonly DependencyProperty PartialViewModelProperty = DependencyProperty.Register("PartialViewModel", typeof(UIElement), typeof(ViewModelBase), new UIPropertyMetadata(null)); This dependency property is used in the MainWindow.xaml to display the User Control dynamicly like this: <UserControl Content="{Binding PartialViewModel}" /> There are also two buttons on this Window that fires the Commands: ShowMessagesCommand ShowUsersCommand And when these are fired, the UserControl changes because PartialViewModel is a dependency property. I want to know if this is bad practice? Should I not inject the User Control like this? Is there another "better" alternative that corresponds better with the design pattern? Or is this a nice way of including partial views?

    Read the article

  • binding a command inside a listbox item to a property on the viewmodel parent

    - by giddy
    I've been working on this for about an hour and looked at all related SO questions. My problem is very simple: I have HomePageVieModel: HomePageVieModel +IList<NewsItem> AllNewsItems +ICommand OpenNewsItem My markup: <Window DataContext="{Binding HomePageViewModel../> <ListBox ItemsSource="{Binding Path=AllNewsItems}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock> <Hyperlink Command="{Binding Path=OpenNews}"> <TextBlock Text="{Binding Path=NewsContent}" /> </Hyperlink> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> The list shows fine with all the items, but for the life of me whatever I try for the Command won't work: <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel, AncestorLevel=1}}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=FindAncestor}**}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=TemplatedParent}**}"> I just always get : System.Windows.Data Error: 4 : Cannot find source for binding with reference .....

    Read the article

  • WPF -- Where do you draw the line between code and XAML?

    - by John Franks
    I'm a long-time C#/.NET programmer but totally new to WPF and the System.Windows.Controls namespace and XAML. The more I learn about it the more I realize that you can do pretty much all of your GUI initialization and event handling glue in either XAML or in code (say C# code or VB.Net code). My question is to those who have been working on WPF for longer and ideally those who have shipped apps with it -- where did you find was the best place to 'draw the line' between XAML and code? Did you use XAML wherever you could? Only where interfacing with non-coding UI designers? Any tips in this area would be extremely helpful to myself and other coders who are just getting into WPF programming and are kind of paralyzed by all the choices we can make!

    Read the article

  • binding a command inside a listbox item to a property on the viewmodel parent

    - by gideon
    I've been working on this for about an hour and looked at all related SO questions. My problem is very simple: I have HomePageVieModel: HomePageVieModel +IList<NewsItem> AllNewsItems +ICommand OpenNews My markup: <Window DataContext="{Binding HomePageViewModel../> <ListBox ItemsSource="{Binding Path=AllNewsItems}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock> <Hyperlink Command="{Binding Path=OpenNews}"> <TextBlock Text="{Binding Path=NewsContent}" /> </Hyperlink> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> The list shows fine with all the items, but for the life of me whatever I try for the Command won't work: <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel, AncestorLevel=1}}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=FindAncestor}**}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=TemplatedParent}**}"> I just always get : System.Windows.Data Error: 4 : Cannot find source for binding with reference ..... Update I am setting my ViewModel like this? Didn't think this would matter: <Window.DataContext> <Binding Path="HomePage" Source="{StaticResource Locator}"/> </Window.DataContext> I use the ViewModelLocator class from the MVVMLight toolkit which does the magic.

    Read the article

  • How to use a 3rd party control inside the viewmodel?

    - by Sander
    I have a 3rd party control which among other things performs loading of some data. I want my viewmodel to keep track of this load operation and adjust its own state accordingly. If it were up to me, I'd do the data loading far away from the view, but it is not. So, I seem to be in the situation where my viewmodel depends on my view. How do I best handle this? I feel rather dirty making the view publish events to the viewmodel but I don't see any other reasonable way to get this info into the viewmodel. A similar situation might crop up with standard controls, too - imagine if your viewmodel depends on the events coming from a MediaElement - how do you properly model this? Do you put the MediaElement into the viewmodel? That doesn't sound right. If publishing the events to the viewmodel is indeed the most reasonable way, is there some common pattern used for this? How do you do it?

    Read the article

  • Windows 8 Data Binding Bug - OnPropertyChanged Updates Wrong Object

    - by Andrew
    I'm experiencing some really weird behavior with data binding in Windows 8. I have a combobox set up like this: <ComboBox VerticalAlignment="Center" Margin="0,18,0,0" HorizontalAlignment="Right" Height="Auto" Width="138" Background="{StaticResource DarkBackgroundBrush}" BorderThickness="0" ItemsSource="{Binding CurrentForum.SortValues}" SelectedItem="{Binding CurrentForum.CurrentSort, Mode=TwoWay}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock HorizontalAlignment="Right" Text="{Binding Converter={StaticResource SortValueConverter}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> Inside of a page with the DataContext set to a statically located ViewModel. When I change that ViewModel's CurrentForm attribute, who's property is implemented like this... public FormViewModel CurrentForm { get { return _currentForm; } set { _currentForm = value; if (!_currentForm.IsLoaded) { _currentSubreddit.Refresh.Execute(null); } RaisePropertyChanged("CurrentForm"); } } ... something really strange happens. The previous FormViewModel's CurrentSort property is changed to the new FormViewModel's current sort property. This happens as the RaisePropertyChanged event is called, through a managed-to-native transition, with native code invoking the setter of CurrentSort of the previous FormViewModel. Does that sound like a bug in Win8's data binding? Am I doing something wrong?

    Read the article

  • How can I simulate the effects of an observable collection in this situation?

    - by MGSoto
    I am making a configuration editor for another application and am using reflection to pull editable fields from the configuration class. The following class is the base class for my various "DataTypeViewModels" and shows how I get and set the appropriate properties. public abstract class DataTypeViewModel<T> : ViewModelBase { Func<T> getFunction; Action<T> setAction; public const string ValuePropertyName = "Value"; public string Label { get; set; } public T Value { get { return getFunction.Invoke(); } set { if (getFunction.Invoke().Equals(value)) { return; } setAction.Invoke(value); // Update bindings, no broadcast RaisePropertyChanged(ValuePropertyName); } } /// <summary> /// Initializes a new instance of the StringViewModel class. /// </summary> public DataTypeViewModel(string sectionName, string label) { if (IsInDesignMode) { // Code runs in Blend --> create design time data. } else { Label = label; getFunction = new Func<T>(() => { return (T)Settings.Instance.GetType().GetProperty(sectionName).PropertyType. GetProperty(label).GetValue(Settings.Instance.GetType().GetProperty(sectionName).GetValue(Settings.Instance, null), null); }); setAction = new Action<T>(value => { Settings.Instance.GetType().GetProperty(sectionName).PropertyType.GetProperty(label). SetValue(Settings.Instance.GetType().GetProperty(sectionName).GetValue(Settings.Instance, null), value, null); }); } } } This part works the way I want it to, the next part is a sample DataTypeViewModel on a list of strings. public class StringListViewModel : DataTypeViewModel<ICollection<string>> { /// <summary> /// The <see cref="RemoveItemCommand" /> property's name. /// </summary> public const string RemoveItemCommandPropertyName = "RemoveItemCommand"; private RelayCommand<string> _removeItemCommand = null; public ObservableCollection<string> ObservableValue { get; set; } /// <summary> /// Gets the RemoveItemCommand property. /// TODO Update documentation: /// Changes to that property's value raise the PropertyChanged event. /// This property's value is broadcasted by the Messenger's default instance when it changes. /// </summary> public RelayCommand<string> RemoveItemCommand { get { return _removeItemCommand; } set { if (_removeItemCommand == value) { return; } var oldValue = _removeItemCommand; _removeItemCommand = value; // Update bindings, no broadcast RaisePropertyChanged(RemoveItemCommandPropertyName); } } /// <summary> /// The <see cref="AddItemCommand" /> property's name. /// </summary> public const string AddItemCommandPropertyName = "AddItemCommand"; private RelayCommand<string> _addItemCommand = null; /// <summary> /// Gets the AddItemCommand property. /// TODO Update documentation: /// Changes to that property's value raise the PropertyChanged event. /// This property's value is broadcasted by the Messenger's default instance when it changes. /// </summary> public RelayCommand<string> AddItemCommand { get { return _addItemCommand; } set { if (_addItemCommand == value) { return; } var oldValue = _addItemCommand; _addItemCommand = value; // Update bindings, no broadcast RaisePropertyChanged(AddItemCommandPropertyName); } } /// <summary> /// Initializes a new instance of the StringListViewModel class. /// </summary> public StringListViewModel(string sectionName, string label) : base(sectionName, label) { ObservableValue = new ObservableCollection<string>(Value); AddItemCommand = new RelayCommand<string>(param => { if (param != string.Empty) { Value.Add(param); ObservableValue.Add(param); } }); RemoveItemCommand = new RelayCommand<string>(param => { if (param != null) { Value.Remove(param); ObservableValue.Remove(param); } }); } } As you can see in the constructor, I currently have "Value" mirrored into a new ObservableCollection called "ObservableValue", which is then bound to by a ListView in the XAML. It works well this way, but cloning the List seems like such a hacky way to do this. While bound to Value, I've tried adding: RaisePropertyChanged("Value"); to the AddItemCommand and RemoveItemCommand, but this doesn't work, the ListView won't get updated. What is the proper way to do this?

    Read the article

  • Unset/Change Binding in WPF

    - by captcalamares
    How can I unset the binding applied to an object so that I can apply another binding to it from a different location? Suppose I have two data templates binded to the same object reference. Data Template #1 is the default template to be loaded. I try to bind a button command to a Function1 from my DataContext class: <Button Content="Button 1" CommandParameter="{Binding }" Command="{Binding DataContext.Function1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/> This actually works and the function gets binded. However, when I try to load Data Template # 2 to the same object (while trying to bind another button command to a different function (Function2) from my DataContext class): <Button Content="Button 2" CommandParameter="{Binding }" Command="{Binding DataContext.Function2, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" /> It doesn't work and the first binding is still the one executed. Is there a workaround to this? EDIT (for better problem context): I defined my templates in my Window.Resources: <Window.Resources> <DataTemplate DataType="{x:Type local:ViewModel1}"> <local:View1 /> </DataTemplate> <DataTemplate DataType="{x:Type local:ViewModel2}"> <local:View2 /> </DataTemplate> </Window.Resources> The View1.xaml and the View2.xaml contain the button definitions that I described above (I want them to command the control of my process flow). ViewModel1 and ViewModel2 are my ViewModels that implement the interface IPageViewModel which is the type of my variable CurrentPageViewModel. In my XAML, I binded ContentControl to the variable CurrentPageViewModel: <ContentControl Content="{Binding CurrentPageViewModel}" HorizontalAlignment="Center"/> In my .CS, I have a list defined as List<IPageViewModel> PageViewModels, which I use to contain the instances of my two View Models: PageViewModels.Add(new ViewModel1()); PageViewModels.Add(new ViewModel2()); // Set starting page CurrentPageViewModel = PageViewModels[0]; When I try to change my CurrentPageViewModel to the other view model, this is when I want the new binding to work. Unfortunately, it doesn't. Am I doing things the right way?

    Read the article

  • Receive messages for derived types in MVVMLight

    - by Hrvoje
    Shouldn't this test pass: [TestMethod] public void derived_message_subscription() { bool handled = false; Messenger.Default.Register<GenericMessage<baseClass>>(this, true, (msg) => handled = true); Messenger.Default.Send(new GenericMessage<testClass>(new testClass())); Assert.IsTrue(handled); } public abstract class baseClass { } public class testClass : baseClass { } I have to receive all messages for classes that inherits from one base class. MVVMLight has bool property receiveDerivedMessagesToo in Register method, but it seems to me that it isn't working.

    Read the article

< Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >