This question already has answers here:
Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.String'
(2 answers)
Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.Nullable`1[System.Guid]'
(1 answer)
Closed 6 months ago.
I am using Visual Studio 2022 Community Edition.
I have the following structure in my app
An class holding some data
class MyData {
public string Property1 { get; set; }
public int Property2 { get; set; }
}
A user control that has a property of type MyData
class MyControl: UserControl {
public MyData Data { get; set; } = new MyData();
// more code here
}
A window where I want to be able to include the user control, to display its MyData type property.
Code behind is:
class MainWindow: Window {
public MyData Data { get; set; } = new MyData();
// more code here
The MainWindow XAML contains:
<MyControl Data="{Binding Data}" />
The designer puts a squiggly line under the Data attribute in the XAML and in the Errors window it gives me the following error:
XDG0062 Object of type 'System.Windows.Data.Binding' cannot be converted to type 'MyData'.
Building the project succeeds without any errors.
What am I doing wrong? How can I bind the MainWindow's property to the MyControl's property?
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Passing two command parameters using a WPF binding
I need that send two parameters to my RelayCommand like:
public RelayCommand<String,Int> MyCommand {get;set;} Or
public RelayCommand<EventArgument,String> MyCommand {get;set;}
Wrap them in an object:
public RelayCommand<MyModel> MyCommand { get; set; }
where MyModel will contain the two properties:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
You can use a distinct model class in order to pass several parameters. And in order to initialize them, you can use xaml elements like this:
<Button Command="{Binding YourCommand}">
<Button.CommandParameter>
<YourNS:YourModel Id="{Binding PathForId}" Name="{Binding PathForName}"/>
</Button.CommandParameter>
</Button>
This will construct a new YourModel object to pass to a command, and then will initialize its properties via bindings.
I'm finally making the switch from Winforms to WPF (3.5) , and I am trying to move this functionality over:
A common practice of mine is to control formatting of a list/combo box display in the Format event, by passing a delegate to the control's container. In the Format Event, the delegate formats the display text of the list item as I want it to appear (e.g. by combining properties of the displaying item).
Is there any equivalent way with the WPF Combo/List box to specify a delegate for formatting the appearance of List Item text at run time?
Thanks,
YS
FYI - Here what I was trying to get at, as described in my answer:
CodeBehind:
public partial class MainWindow : Window
{
private List<Foo> l = new List<Foo>();
//Formatting done by delegate, passed to converter.
MyConverter<Foo> cv = new MyConverter<Foo>(f=> "#" + f.ID + " = " + f.Name);
public MainWindow()
{
Resources.Add("myConverter", cv);
l.Add(new Foo(){ID=1, Name = "aaaa aaaa"});
l.Add(new Foo(){ID=2, Name = "bbbb bbbb "});
DataContext = l;
InitializeComponent();
}
}
public class Foo
{
public int ID { get; set; }
public string Name { get; set; }
}
public class MyConverter<T> : IValueConverter
{
private Func< T, string> _formatter { get; set; }
public MyConverter(Func<T, string> Formatter)
{
_formatter = Formatter;
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return _formatter((T)value);
}
}
And then in the xaml:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource ResourceKey=myConverter}}"> </TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
If you are looking to format each item the same, look into ListBox.ItemContainerStyle. This will contain the template for each item. If you are looking into changing the styles for each item based on some logic, use the above along with ListBox.ItemContainerStyleSelector. See msdn doc http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemcontainerstyle.aspx and http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemcontainerstyleselector.aspx
For everyone breathlessly following this question...
I posted the question on the MS WPF forum, and from the answer there I think the best path for me is to create a custom IValueConverter where I can pass in a delegate to use in the Convert method, and set that as the Converter in the DataTemplate.
I have the following class,
internal class PageInformation
{
public string Name
{
get;
set;
}
public Uri PageUri
{
get;
set;
}
}
How can I use it in XAML (a page) and assign values to its properties?
Update-1:
I added xmlns attribute in page tag
<Page xmlns:local="clr-namespace:Demo.Pages">
and inherited PageInformation from DependencyObject (to have dependency properties).
Still XAML does not recognize the PageInformation class
I was trying to use PageInformation element in a Canvas. Since it is not a UIElement, I think, It can't be added there.
I can use it as a resource element instead (in Page.Resources) :)
I have a UserControl with multiple fields that I would like to have bound to a BindingSource. I would also like the UserControl to expose some BindingSource property so that it can be dropped on a Form and be bound to the BindingSource on the form. Is there an easy way to do this? I realize that I can rebind all of the controls of the UserControl in its BindSource setter. But this seems wrong. Is there some BindingSource Proxy that will let me link the BindingSource in the user control to the BindingSource in the form?
As per your question, I can hardly get what you intend to do. Thus I will try my best to provide you with, I hope, interesting information on that matter.
First, let's consider the following UserControl in a Customer management software project.
public partial class CustomerManagementUserControl : UserControl {
public CustomerManagementUserControl() {
InitializeComponent();
_customerBindingSource = new BindingSource();
}
public IList<ICustomer> DataSource {
set {
_customerBindingSource.DataSource = value;
}
}
private BindingSource _customerBindingSource;
}
Second, let's consider the following Form which should be your Customer management form.
public partial class CustomerManagementForm : Form {
public CustomerManagementForm() {
InitializeComponent();
_customerUserControl = new CustomerManagementUserControl();
_customerUserControl.Name = #"customerUserControl";
}
private void CustomerManagementForm_Load(object sender, EventArgs e) {
// CustomersFacade is simply a static class providing customer management features and requirements.
// Indeed, the GetCustomers() method shall return an IList<ICustomer>.
// The IList type and typed IList<T> are both intended to be bindable as a DataSource for DataBinding.
_customerUserControl.DataSource = CustomersFacade.GetCustomers();
this.Controls.Add(_customerUserControl);
}
private CustomerManagementUserControl _customerUserControl;
}
If you're expecting to use CustomerManagementUserControl.DataSource property from within the Property window, please consider adding the following on top of your property definition.
[System.ComponentModel.DesignTimeVisible(true), System.ComponentModel.DesignerCategory("CustomerUserControl"), System.ComponentModel.Description("Sets the CustomerUserControl DataSource property")]
This is one way of doing what I guess you might want to do. On the other hand, if what you wish to do is to get the as most abstract as possible by setting a different type of object as your UserControl.BindingSource.DataSource property, then you will have to write a method which could detect the type of the object passed, then binding the properties accordingly. A nice way you could go, perhaps, is by Reflection, if you're comfortable working with it. In any possible way you may imagine working with such polymorphism features, you will have to write yourself an interface that all of your bindable objects will have to implement. This way, you will avoid unknown property names, and when will come the time to bind your UserControl's controls, you will be able to bind the correct property to the correct control and so forth.
Let's try the following:
public interface IEntity {
double Id { get; set; }
string Number { get; set; }
string Firstname { get; set; }
string Surname { get; set; }
long PhoneNumber { get; set; }
}
public interface ICustomer : IEntity {
}
public interface ISupplier : IEntity {
string Term { get; set; }
}
public sealed Customer : ICustomer {
public Customer() {
}
public double Id { get; set; }
public string Number { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public long PhoneNumber { get; set; }
}
public sealed Supplier : ISupplier {
public Supplier() {
}
public double Id { get; set; }
public string Number { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
public long PhoneNumber { get; set; }
public string Term { get; set; }
}
Considering the above code, you could use the DataSource property of your UserControl to bind with an IEntity, so your property could like like this.
[System.ComponentModel.DesignTimeVisible(true), System.ComponentModel.DesignerCategory("CustomerUserControl"), System.ComponentModel.Description("Sets the CustomerUserControl DataSource property")]
public IList<IEntity> DataSource {
set {
_customerBindingSource.DataSource = value;
}
}
That said, if you wish to push even further, you could just expose your UserControl's controls DataBindings properties in order to set them on design-time. Considering this, you will want to expose your BindingSource as a public property either so that you may set it on design-time too, then choose your DataMember from this BindinSource.
I hope this helps you both a little or at least, give you some tracks for further searchings.
I know it's a late answer; however, it might be useful to someone else reading this post.
I have controls on a UserControl that are data-bound. I need to have a BindingSource on the UserControl in order to be able to bind the controls at design time. The "real" BindingSource, however, sits on the Form. In other words, the controls on the UserControl should behave as if they were sitting directly on the form (or on a ContainerControl on the form).
The idea behind this solution is to watch for the DataSourceChanged event of the "real" BindingSource and to assign its DataSource to the local BindingSource when it changes. In order to find the "real" BindingSource I let the Form (or Control) containing it implement the following interface:
public interface IDataBound
{
BindingSource BindingSource { get; }
}
We can watch for the ParentChanged event of a control in order to know when it has been added to a Form or a ContainerControl. The problem here is that this ContainerControl itself might not have been added to the Form (or another ContainerControl) yet at this time. In this case we subscribe to the ParentChanged event of the last parent we find in the parents chain and wait until this last parent has been added, an so on, until we find a Control or Form implementing IDataBound. When a IDataBound has been found, we subscribe to the DataSourceChanged event of its BindingSource.
public partial class MyUserControl : UserControl
{
private IDataBound _dataBoundControl;
private Control _parent;
public MyUserControl()
{
InitializeComponent();
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) {
_parent = this;
SearchBindingSource();
}
}
private void SearchBindingSource()
{
if (_parent != null && _dataBoundControl == null) {
while (_parent.Parent != null) {
_parent = _parent.Parent;
_dataBoundControl = _parent as IDataBound;
if (_dataBoundControl != null) {
if (_dataBoundControl.BindingSource != null) {
_dataBoundControl.BindingSource.DataSourceChanged +=
new EventHandler(DataBoundControl_DataSourceChanged);
}
return;
}
}
// This control or one of its parents has not yet been added to a
// container. Watch for its ParentChanged event.
_parent.ParentChanged += new EventHandler(Parent_ParentChanged);
}
}
void Parent_ParentChanged(object sender, EventArgs e)
{
SearchBindingSource();
}
void DataBoundControl_DataSourceChanged(object sender, EventArgs e)
{
localBindingSource.DataSource = _dataBoundControl.BindingSource.DataSource;
}
}
If you wanted to do this all automatically you could look for the binding source from the parent form in the load event of your user control or something like that...
Dim components As Reflection.FieldInfo = typ.GetField("components", Reflection.BindingFlags.DeclaredOnly Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
Dim lstBindingSources As New List(Of BindingSource)
For Each obj As Object In components.Components
Dim bindSource As BindingSource = TryCast(obj, BindingSource)
If bindSource IsNot Nothing Then
lstBindingSources.Add(bindSource)
End If
Next
If lstBindingSources.Count = 1 Then
MyBindingSource.DataSource = lstBindingSources(0).DataSource
End If
If you assign the same object reference as the datasource on two bindingsources, the controls will not be updated consistently on the second bindingsource. Possibly, a compromise to the choices above is the following:
Temporarily add a bindingsource to the usercontrol and use the VS designer to set the bindings to the controls.
bring the designer.vb up in the code editor. Search for all the "DataBindings.Add" lines that were created by the designer. Copy them all to notepad.
delete the bindingsource from the designer and add a bindingsource reference in code. Add a property for the bindingsource with the same name as was used in the designer. In the setter for the property, paste all the lines from notepad above in step 2.
In the Load event of the form, assign the bindingsource of the form to the property on the user control. If the user control is embedded in another user control, you can use the handlecreated event of the parent control to do the same.
There is less typing and less typos because the VS designer is creating all those literal text property names.
I have a textbox in XAML file, On Changing the text in the textbox the prop setter is not getting called. I am able to get the value in ProjectOfficer textbox and not able to update it. I am using MVVM pattern
Below is my code XAML
TextBox Text="{Binding Path=Officer,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
x:Name="ProjectOfficer"/>
ViewModel.cs
public Staff Officer
{
get
{
return __con.PrimaryOfficer ;
}
set
{
_con.PrimaryOfficer = value;
_con.PrimaryOfficer.Update(true);
}
}
Staff.cs
public class Staff : EntityBase
{
public Staff();
public string Address { get; }
public string Code { get; set; }
public override void Update();
}
Thanks
You're binding a property of type string on the TextBox to a property of type Officer on your ViewModel. I expect the setter isn't being called because WPF can't do the conversion.
If you check the output window in visual studio, you'll probably see a binding error for this property.
Try something like:
TextBox text ="{Binding Path=Address,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
x:Name="ProjectOfficer"/>
Make sure the holder of the TextBox is linked to a Staff object. The textbox cannot bind directly to an object without telling the property to display (like Address in my example above).