data-binding interview questions
Top data-binding frequently asked interview questions
When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged instead.
My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?
Source: (StackOverflow)
I've got an enum like this:
public enum MyLovelyEnum
{
FirstSelection,
TheOtherSelection,
YetAnotherOne
};
I got a property in my DataContext:
public MyLovelyEnum VeryLovelyEnum { get; set; }
And I got three RadioButtons in my WPF client.
<RadioButton Margin="3">First Selection</RadioButton>
<RadioButton Margin="3">The Other Selection</RadioButton>
<RadioButton Margin="3">Yet Another one</RadioButton>
Now how do I bind the RadioButtons to the property for proper two-way-binding?
Source: (StackOverflow)
I want to connect a binding source to a list of class objects and then objects value to a combo box can anyone suggest how to do it
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
is my class and i want to bind its name field to a binding source which could be then associated with a combobox
Source: (StackOverflow)
I'm considering either a ListBox or a ListView for a WPF application. It seems either supports data binding and item templates. My application has a simple list of items that I intend to be able to search/sort/filter based on user input. The data binding demo (http://msdn.microsoft.com/en-us/library/ms771319.aspx) uses a ListBox with a CollectionViewSource.
Does anyone have pros/cons for which control to use and when?
Source: (StackOverflow)
Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )?
I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.
This is what I have as a proof of concept so far, but the "<WebBrowser Source="{Binding Path=WebAddress}"
" does not compile.
<DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress">
<StackPanel Orientation="Horizontal">
<!--Web Control Here-->
<WebBrowser Source="{Binding Path=WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200"
/>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" />
<TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" />
</StackPanel>
<TextBox Text="{Binding Path=Street[0]}" />
<TextBox Text="{Binding Path=Street[1]}" />
<TextBox Text="{Binding Path=PhoneNumber}"/>
<TextBox Text="{Binding Path=FaxNumber}"/>
<TextBox Text="{Binding Path=Email}"/>
<TextBox Text="{Binding Path=WebAddress}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
Source: (StackOverflow)
How do you bind to an objects method in this scenario in WPF?
public class RootObject
{
public string Name { get; }
public ObservableCollection<ChildObject> GetChildren() {...}
}
public class ChildObject
{
public string Name { get; }
}
XAML:
<TreeView ItemsSource="some list of RootObjects">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type data:RootObject}"
ItemsSource="???">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type data:ChildObject}">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Here I want to bind to the GetChildren
method on each RootObject
of the tree.
EDIT Binding to an ObjectDataProvider
doesn't seem to work because I'm binding to a list of items, and the ObjectDataProvider
needs either a static method, or it creates it's own instance and uses that.
For example, using Matt's answer I get:
System.Windows.Data Error: 33 : ObjectDataProvider cannot create object; Type='RootObject'; Error='Wrong parameters for constructor.'
System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetChildren'; Type='RootObject'; Error='The specified member cannot be invoked on target.' TargetException:'System.Reflection.TargetException: Non-static method requires a target.
Source: (StackOverflow)
I am working without expression blend and just using the XAML editor in vs2010. The wisdom of this aside, I am increasingly seeing a need for design-time data binding. For simple cases, the FallbackValue
property works very nicely (Textboxes and TextBlocks, etc). But especially when dealing with ItemsControl
and the like, one really needs sample data to be visible in the designer so that you can adjust and tweak controls and data templates without having to run the executable.
I know that ObjectDataProvider
allows for binding to a type, and thus can provide design-time data for visualizing, but then there is some juggling to allow for the real, run-time data to bind without wasting resources by loading loading both the design time, dummied data and the runtime bindings.
Really what I am wanting is the ability to have, say, "John", "Paul", "George", and "Ringo" show up in the XAML designer as stylable items in my ItemsControl
, but have real data show up when the application runs.
I also know that Blend allows for some fancy attributes that define design time binding data that are effectively ignored by WPF in run-time conditions.
So my questions are:
1. How might I leverage design-time bindings of collections and non-trivial data in the visual studio XAML designer and then swap to runtime bindings smoothly?
2. How have others solved this design-time vs. runtime data problem? In my case, i cannot very easily use the same data for both (as one would be able to with, say, a database query).
3. Are their alternatives to expression blend that i could use for data-integrated XAML design? (I know there are some alternatives, but I specifically want something I can use and see bound sample data, etc?)
Source: (StackOverflow)
In AngularJS, how can I render a value without 2-way data binding? One may want to do this for performance reasons, or even rendering a value at a given point in time.
The following examples both use data binding:
<div>{{value}}</div>
<div data-ng-bind="value"></div>
How do I render value
without any data binding?
Source: (StackOverflow)
I have read lots that Backbone doesn't do two way binding but I don't exactly understand this concept.
Could somebody give me an example of how two way binding works in an MVC codebase and how it does not with Backbone?
Source: (StackOverflow)
I've got a situation in which I need to show an integer value, bound to a property on my data context, after putting it through two separate conversions:
- Reverse the value within a range (e.g. range is 1 to 100; value in datacontext is 90; user sees value of 10)
- convert the number to a string
I realise I could do both steps by creating my own converter (that implements IValueConverter). However, I've already got a separate value converter that does just the first step, and the second step is covered by Int32Converter.
Is there a way I can chain these two existing classes in XAML without having to create a further class that aggregates them?
If I need to clarify any of this, please let me know. :)
Thanks.
Source: (StackOverflow)
I am trying to find a simple example where the enums are shown as is. All examples I have seen tries to add nice looking display strings but I don't want that complexity.
Basically I have a class that holds all the properties that I bind, by first setting the DataContext to this class, and then specifying the binding like this in the xaml file:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
But this doesn't show the enum values in the ComboBox
as items.
Source: (StackOverflow)
My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used to apply formatting. A simplified version of the output might be something like:
class Data
{
IList<ColumnDescription> ColumnDescriptions { get; set; }
string[][] Rows { get; set; }
}
This class is set as the DataContext on a WPF DataGrid but I actually create the columns programmatically:
for (int i = 0; i < data.ColumnDescriptions.Count; i++)
{
dataGrid.Columns.Add(new DataGridTextColumn
{
Header = data.ColumnDescriptions[i].Name,
Binding = new Binding(string.Format("[{0}]", i))
});
}
Is there any way to replace this code with data bindings in the XAML file instead?
Source: (StackOverflow)
I am binding a List<string>
to a Repeater control. Now I want to use the Eval
function
to display the contents in ItemTemplate
like
<%# Eval("NAME") %>.
But I am not sure what I should use instead of NAME.
Source: (StackOverflow)
One of the interesting things Angular.js can do is apply a filter to a particular databinding expression, which is a convenient way to apply, for example, culture-specific currency or date formatting of a model's properties. It is also nice to have computed properties on the scope. The problem is that neither of these features work with two-way databinding scenarios - only one-way databinding from the scope to the view. This seems to be a glaring omission in an otherwise excellent library - or am I missing something?
In KnockoutJS, I could create a read/write computed property, which allowed me to specify a pair of functions, one which is called to get the value of the property, and one which is called when the property is set. This allowed me to implement, for example, culture-aware input - letting the user type "$1.24" and parsing that into a float in the ViewModel, and have changes in the ViewModel reflected in the input.
The closest thing I could find similar to this is the use of $scope.$watch(propertyName, functionOrNGExpression); This allows me to have a function invoked when a property in the $scope changes. But this doesn't solve, for example, the culture-aware input problem. Notice the problems when I try to modify the $watched property within the $watch method itself:
$scope.$watch("property", function (newValue, oldValue) {
$scope.outputMessage = "oldValue: " + oldValue + " newValue: " + newValue;
$scope.property = Globalize.parseFloat(newValue);
});
(http://jsfiddle.net/gyZH8/2/)
The input element gets very confused when the user starts typing. I improved it by splitting the property into two properties, one for the unparsed value and one for the parsed value:
$scope.visibleProperty= 0.0;
$scope.hiddenProperty = 0.0;
$scope.$watch("visibleProperty", function (newValue, oldValue) {
$scope.outputMessage = "oldValue: " + oldValue + " newValue: " + newValue;
$scope.hiddenProperty = Globalize.parseFloat(newValue);
});
(http://jsfiddle.net/XkPNv/1/)
This was an improvement over the first version, but is a bit more verbose, and notice that there is still an issue of the parsedValue property of the scope changes (type something in the second input, which changes the parsedValue directly. notice the top input does not update). This might happen from a controller action or from loading data from a data service.
Is there some easier way to implement this scenario using Angular.js? Am I missing some functionality in the documentation?
Source: (StackOverflow)