Error trying to bind Content to Window for 2nd time - wpf

have the following in my CodeBehind (class name MainHostWindow)
private object _hostContent = null;
public object HostContent
{
get { return _hostContent; }
set { _hostContent = value;}
}
this binds into a ContentControl of my View.
in a different class I do the following:
MainHostWindow host = new MainHostWindow();
{
host.HostContent = MyView; // this is an instance of a UserControl
host.Owner = this._mainWindow;
host.DataContext = viewModel;
}
host.ShowDialog();
first time it shows the MainHostWindow with the correct Content, 2nd time I get the following exception:
Specified element is already the logical child of another element. Disconnect it first.

It looks as if you are trying to add the same UserControl (not a new instance of it) to another instance of your MainHostWindow. The error is correct because the same element cannot be the child of two different containers (what would UserControl.Parent return?). You will need to create a new instance of your UserControl.
host.HostContent = new MyView();
are you able to set MyView declaratively in the XAML for MainHostWindow as this would always create a new instance when the Control is created.

Related

Finding a ListView row in coded UI causes 'No row was specified as search container for the control.'

I have a ListView inside of a Popup control (seems to be significant that it's in a Popup). The coded test is pretty basic, click a ToggleButton to open the popup, and then select an item in the ListView.
Except it seems that it can't find the item in the ListView.
System.ArgumentException: No row was specified as search container for
the control. To search for a cell control using 'ColumnIndex', you
must specify row as a container element or add 'RowIndex' to the
search property of the cell. Parameter name: SearchProperties Result
StackTrace: at
Microsoft.VisualStudio.TestTools.UITesting.ALUtility.ThrowDataGridRelatedException(String
errorString, String propertyName) at
Microsoft.VisualStudio.TestTools.UITesting.WpfControls.WpfCell.GetUITestControlsForSearch()
at
Microsoft.VisualStudio.TestTools.UITesting.UITestControl.get_QueryId()
at
Microsoft.VisualStudio.TestTools.UITesting.UITestControlSearchArgument.get_SingleQueryString()
at
Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean
useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1
windowTitles, Int32& timeLeft)
The generated code is failing at this point
uIItemCell.Checked = this.MyListBoxCellParams.UIItemCellChecked;
where uIItemCell comes from this property
public WpfCell UIItemCell
{
get
{
if ((this.mUIItemCell == null))
{
this.mUIItemCell = new WpfCell(this);
#region Search Criteria
this.mUIItemCell.SearchProperties[WpfCell.PropertyNames.ColumnHeader] = null;
this.mUIItemCell.SearchProperties[WpfCell.PropertyNames.ColumnIndex] = "1";
this.mUIItemCell.WindowTitles.Add("CodedUITestWindow");
#endregion
}
return this.mUIItemCell;
}
}
So I guess this is where the criteria should be specified, but what how? And should row be hard coded somehow? Why didn't the test editor set the row?
If it helps, this is the .ctor where UIItemCell (above) is specified, seems like more search params
public UIMyCellDataItem(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.SearchProperties[UITestControl.PropertyNames.ControlType] = "DataItem";
this.SearchProperties["HelpText"] = "MyCell's helptext property, this is correctly specified, but the HelpText is used only as a tooltip";
this.WindowTitles.Add("CodedUITestWindow");
#endregion
}
Thanks
I've normally seen ListView treated as a List, and the items as ListItem. You might want to use inspect.exe or the UI Test Builder to look at the properties. You can try to manually code the control. Sorry for posting speculation as an answer. Too long to be a comment.
WpfWindow PopUpWindow = new WpfWindow();
PopUpWindow.SearchProperties[WpfWindow.PropertyNames.Name] = "Pop Up Window Name";
WpfList List = new WpfList(PopUpWindow);
List.SearchProperties[WpfList.PropertyNames.Name] = "List Name";
WpfListItem ItemToSelect = new WpfListItem(List);
ItemToSelect.SearchProperties[WpfListItem.PropertyNames.Name] = "List Item Name";
// Click button to activate pop up window
ItemToSelect.Select();
// Creating the controls.
WpfWindow mainWindow = new WpfWindow();
// Add search properties.
WpfTable table = new WpfTable(mainWindow);
// Add search properties
WpfRow row = new WpfRow(table);
// Add search properties.
WpfCell cell = new WpfCell(row);
// Add search properties.
// Just adding the table and row as containers.
row.Container = table;
cell.Container = row;
}

ObservableCollection does not update

I have ObservableCollection<Customer> on my window.
ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers { get { return customers; } set { customers = value; OnPropertyChanged("Customers"); } }
This ObservableCollection has bound to ListView on the window. Once Use select on Customer from listView and click on edit a new window will appear with selected customer's data.
Second window's constructor
public EditCustomerWindow(Customer c)
{
InitializeComponent();
customerobj = c; //Original object
tempCustomerobj = new Customer(c); //Getting a copy of the customer object
CustomerDataGrid.DataContext = tempCustomerobj;
}
Once user clicks on Save Button customer object will get updated and window will closes.
But my issue is ObserverCollection does not get update on fist window even though I set new edited customer object before editing window get closed. Cannot find what is the wrong I am doing. Please advice me.
customerobj = tempCustomerobj;
You appear to be creating a new Customer object that is not in your ObservableCollection
tempCustomerobj = new Customer(c);
and then editing that new object.
CustomerDataGrid.DataContext = tempCustomerobj;
Doing that will not in any way affect the original Customer object that is still in your ObservableCollection.
To solve, don't create a new Customer, but rather edit an existing one.
Update
Based on your comments
The line
customerobj = c; //Original object
causes customerobj to be an alias to c, your object that is actually in the ObservableCollection.
The line
customerobj = tempCustomerobj;
causes customerobj to now be an alias to tempCustomerobj, which is your brand-new Customer object that is (I presume) a clone of c.
Change your constructor to
public EditCustomerWindow(Customer c)
{
InitializeComponent();
CustomerDataGrid.DataContext = c;
}
Update 2
The object you're editing should support IEditableObject. See
https://stackoverflow.com/a/1091240/141172
Alternatively, you can serialize the object before you start editing and deserialize the saved state if the edit is canceled.

WPF:Unity: Reuse window after it has been closed

In ShellViewModel I have below command binding to open a new window "Remote View"
public ICommand RemoteViewCommand
{
get { return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute); }
}
private void RemoteViewExecute()
{
if (!CanRemoteViewExecute())
{
return;
}
var shellRemoteView = Application._Container.Resolve<ShellRemoteView>();
if (_ShellRemoteView.DataContext==null)
_ShellRemoteView.DataContext = Application._Container.Resolve<ShellRemoteViewModel>();
shellRemoteView.Show();
}
On startup I have already registered both "ShellRemoteView" and "ShellRemoteViewModel" using lifetime managers to have singleton instance.
_Container.RegisterType<ShellRemoteView>(new ContainerControlledLifetimeManager());
_Container.RegisterType<ShellRemoteViewModel>(new ContainerControlledLifetimeManager());
When shellRemoteView.Show() executed and I close the form, then again on calling shellRemoteView.Show() I'm getting Invalid Operation excepton:Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.
Is there is any work-around in Unity to get window instance again if its closed.
This line is your problem:
return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute);
Basically you are creating a new view each time you call the Get command. The way to fix this is to put a variable outside your GET statement that is scoped at the ViewModel level. Have it store a reference to the view and return that reference instead of creating a new reference each time. Look at the Singleton pattern for how best to do this.
You should register your View with LifetimeManager to create only one instance. Look at Using Lifetime Managers.

How to detect the sender(button) of dynamical created bindings

I create some RibbonButtons dynamically and add them to a group according to an xml file. The follwoing function is carried out as often as entries found in the xml file.
private void ExtAppsWalk(ExternalAppsXml p, AppsWalkEventArgs args)
{
RibbonButton rBtn = new RibbonButton();
rBtn.Name = args.Name;
Binding cmdBinding = new Binding("ExtAppCommand");
rBtn.SetBinding(RibbonButton.CommandProperty, cmdBinding);
Binding tagBinding = new Binding("UrlTag");
tagBinding.Mode = BindingMode.OneWayToSource;
rBtn.SetBinding(RibbonButton.TagProperty, tagBinding);
rBtn.Label = args.Haed;
rBtn.Tag = args.Url;
rBtn.Margin = new Thickness(15, 0, 0, 0);
MyHost.ribGrpExtern.Items.Add(rBtn);
}
I tried to use the Tag property to store the Url's to be started when the respective button is clicked. Unfortunately the binding to the Tag property gives me the last inserted Url only.
What would be the best way to figure out which button is hit or to update the Tag property.
The datacontext is by default the context of the Viewmodel. The RibbonGroup to which the Buttons are added is created in the xaml file at designtime. I use that construct:
MyHost.ribGrpExtern.Items.Add(rBtn);
to add the buttons. It maight not really be conform with the mvvm pattern. May be someone else has a better idea to carry that out.
I foud a solution for my problem here and use the RelayCommand class. So I can pass objects (my Url) to the CommandHandler.
RibbonButton rBtn = new RibbonButton();
rBtn.Name = args.Name;
Binding cmdBinding = new Binding("ExtAppCommand");
rBtn.SetBinding(RibbonButton.CommandProperty, cmdBinding);
rBtn.CommandParameter = (object)args.Url;
private void ExtAppFuncExecute(object parameter)
{
if (parameter.ToString().....//myUrl

Reusing Binding Collections for WPF

I am working on a WPF app using the MVVM patterm, which I am learning. It uses EF4. I am trying to use a similar tabbed document interface style; several combo boxes on these tabs have the same items sources (from a sql db). Since this data almost never changes, it seemed like a good idea to make a repository object to get them when the app starts, and just reuse them for each viewmodel. For whatever reason though, even though I use new in the constructors, the lists are connected.
If I set a bound combo box on one tab, it gets set on another (or set when a new tab is created). I don't want this to happen, but I don't know why does.
The repository object is initialized before anything else, and just holds public lists. The views simply use items source binding onto the ObservableCollection. I am using the ViewModelBase class from the article. Here is the Viewmodel and model code.
ViewModel
TicketModel _ticket;
public TicketViewModel(TableRepository repository)
{
_ticket = new TicketModel(repository);
}
public ObservableCollection<Customer> CustomerList
{
get { return _ticket.CustomerList; }
set
{
if (value == _ticket.CustomerList)
return;
_ticket.CustomerList = value;
//base.OnPropertyChanged("CustomerList");
}
}
Model
public ObservableCollection<Customer> CustomerList { get; set; }
public TicketModel(TableRepository repository)
{
CustomerList = new ObservableCollection<Customer>(repository.Customers);
}
EDIT: I am sure this is the wrong way to do this, I am still working on it. Here is the new model code:
public TicketModel(TableRepository repository)
{
CustomerList = new ObservableCollection<Customer>((from x in repository.Customers
select
new Customer
{
CM_CUSTOMER_ID = x.CM_CUSTOMER_ID,
CM_FULL_NAME = x.CM_FULL_NAME,
CM_COMPANY_ID = x.CM_COMPANY_ID
}).ToList());
}
This causes a new problem. Whenever you change tabs, the selection on the combo box is cleared.
MORE EDITS: This question I ran into when uses Rachels answer indicates that a static repository is bad practice because it leaves the DB connection open for the life of the program. I confirmed a connection remains open, but it looks like one remains open for non-static classes too. Here is the repository code:
using (BT8_Entity db = new BT8_Entity())
{
_companies = (from x in db.Companies where x.CO_INACTIVE == 0 select x).ToList();
_customers = (from x in db.Customers where x.CM_INACTIVE == 0 orderby x.CM_FULL_NAME select x).ToList();
_locations = (from x in db.Locations where x.LC_INACTIVE == 0 select x).ToList();
_departments = (from x in db.Departments where x.DP_INACTIVE == 0 select x).ToList();
_users = (from x in db.Users where x.US_INACTIVE == 0 select x).ToList();
}
_companies.Add(new Company { CO_COMPANY_ID = 0, CO_COMPANY_NAME = "" });
_companies.OrderBy(x => x.CO_COMPANY_NAME);
_departments.Add(new Department { DP_DEPARTMENT_ID = 0, DP_DEPARTMENT_NAME = "" });
_locations.Add(new Location { LC_LOCATION_ID = 0, LC_LOCATION_NAME = "" });
However, now I am back to the ugly code above which does not seem a good solution to copying the collection, as the Customer object needs to be manually recreated property by property in any code that needs its. It seems like this should be a very common thing to do, re-using lists, I feel like it should have a solution.
Custom objects, such as Customer get passed around by reference, not value. So even though you're creating a new ObservableCollection, it is still filled with the Customer objects that exist in your Repository. To make a truly new collection you'll need to create a new copy of each Customer object for your collection.
If you are creating multiple copies of the CustomerList because you want to filter the collection depending on your needs, you can use a CollectionViewSource instead of an ObservableCollection. This allows you to return a filtered view of a collection instead of the full collection itself.
EDIT
If not, have you considered using a static list for your ComboBox items, and just storing the SelectedItem in your model?
For example,
<ComboBox ItemsSource="{Binding Source={x:Static local:Lists.CustomerList}}"
SelectedItem="{Binding Customer}" />
This would fill the ComboBox with the ObservableCollection<Customer> CustomerList property that is found on the Static class Lists, and would bind the SelectedItem to the Model.Customer property
If the SelectedItem does not directly reference an item in the ComboBox's ItemsSource, you need to overwrite the Equals() of the item class to make the two values equal the same if their values are the same. Otherwise, it will compare the hash code of the two objects and decide that the two objects are not equal, even if the data they contain are the same. As an alternative, you can also bind SelectedValue and SelectedValuePath properties on the ComboBox instead of SelectedItem.

Resources