Silverlight 2 - DataContext / Binding problem - binding

I'm having a problem with this this XAML... When I run it, it hangs because of the TextBox. (By "hangs" I mean that the hosting aspx page shows in the browser, but the usercontrol object will not appear on the page, and there are some little green bars in the bottom of the Internet Explorer window that fill up but never go away.) I have both a TextBox and a TextBlock in my code just for testing. It runs fine if I comment out the TextBox and leave only the TextBlock, so I know the DataContext is getting set and the binding to PatternName does work. There are no errors in the Output window to help me debug. Please help! I've spent hours on this problem. What can possible be happening?
<StackPanel x:Name="HolePatternStackPanel" >
<TextBlock Text="{Binding PatternName}" Width="75" />
<TextBox Text="{Binding PatternName}" Height="25" Width="125"/>
</StackPanel>
Here is the code that sets the DataContext from a calling ListBox.SelectionChanged method:
private void lvHolePatterns_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
HolePatternStackPanel.DataContext = this.ActivePattern;
}

Well, I've learned more about this... This whole thing is a Master-Detail UI design, and so I had my ListBox using SelectedItem="{Binding ActivePattern}", and apparently, some infinite loop was getting set up between that and the SelectionChanged eventhandler.
So now my question now becomes what good is SelectedItem anyway? Since I had to add a SelectionChanged eventhandler to update the DataContext of the detail stack panel?

You wouldn't need to use the SelectionChanged event if you set the DataContext of the controls with the SelectedItem
for example
<Grid DataContext="{Binding SelectedItem}">
<TextBlock Text="{Binding some_field_in_selecteditem}" />
</Grid>

Related

x:Bind Design Time issues

I am trying to build my UWP app and currently am stuck with designer exceptions when trying to use DataTemplate with x:Bind in a Resource Dictionary.
I have created a Resource Dictionary "ItemTemplates.xaml" with a respective code-behind (to ensure x:Bind initialization). The file contains just one template:
<DataTemplate x:Key="HomeViewCategoryListItemTemplate" x:DataType="models:Category">
<Button Background="#88333333" Height="110" VerticalContentAlignment="Top" Padding="10" HorizontalAlignment="Stretch">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock FontWeight="Light" HorizontalAlignment="Center" Text="{x:Bind Name}" FontSize="{ThemeResource TextStyleExtraLargeFontSize}" />
<TextBlock Foreground="{ThemeResource ToolTipForegroundThemeBrush}" HorizontalAlignment="Center" Margin="0,10,0,0" Text="{x:Bind Description}" Grid.Row="1" TextAlignment="Center" TextWrapping="Wrap" />
</Grid>
</Button>
</DataTemplate>
Then I added this resource dictionary to App.xaml like this:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Resources/Core.xaml" />
<resources:ItemTemplates />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now the project is unusable, because designer throws weird exceptions, but when I Clean and Rebuild the project and navigate to the HomeView.xaml page, the designer shows just the default "ToString()" items (basically the list view contains just three times the text "Models.Categories") in the ListView and the ItemTemplate property of my ListView is underlined and shows the following error:
The resource "HomeViewCategoryListItemTemplate" could not be resolved.
When I navigate back to App.xaml, I see yet another underline there (of the <resources:ItemTemplates /> line) which says:
The property 'DataType' was not found in type 'DataTemplate'.
Both errors are non-sensical, because when I actually run the app, there are no issues and everything works perfectly. The only workaround I have found so far is to include the ResourceDictionary two times in both the classic way and the "compiled" way:
<ResourceDictionary Source="ItemTemplates.xaml" />
<resoures:ItemTemplates />
This solution works and then everything works both in design time and in run-time, but I really think it is quite messy and there has to be a better, safer approach or I am missing something trivial.
I am running Visual Studio 2015 Update 1 and have the newest UWP SDK installed. The project targets build 10240.
Edit:
Another exception that the designer very often throws and crashes completely:
Unable to cast object of type 'System.String' to type 'Models.Data.Categories.Category'.
According to the StackTrace output this happens inside the ItemTemplates.xaml.cs code - specifically the generated method ProcessBindings. Again, the project still compiles and runs normally, but the designer does not even bother trying to show the output.
For this current version, prefer Binding over x:Bind
an answer from a Microsoft engineers
I've got the same problems as you did, plus a ton of bugs when using x:Bind in Design time. Quickest way to fix: use Binding as old time. And when you release, if performance is under consideration, change the Binding to x:Bind

Windows Phone Binding

In my RoomView.xaml I have:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox ItemsSource="{Binding myStrings, Mode=TwoWay}"></ListBox>
</Grid>
In my constructor I am doing:
var myStrings = new List<string>{"Usmaan","Carl","Andy","Saul"};
DataContext = myStrings;
Yet nothing is being spat out on the page when I load the application.
Can anyone see where I am going horribly wrong?
The DataContext of your page is already set to the List object, so you just need to set the binding like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox ItemsSource="{Binding, Mode=TwoWay}"></ListBox>
</Grid>
Alternatively, you could create an object that has a MyStrings property and use it as the DataContext of the page. Then you could bind the ListBox like you did {Binding myStrings, Mode=TwoWay} while also being able to bind other controls to other properties of that object (that's the principle of ViewModels).

How to binding to relative source

Do you see any problem with my codes when I tried to bind a check box inside a DataGrid to a public property of a the View Model which is the data context of the user control.
thanks,
Jdang
<Custom:DataGrid ItemsSource="{Binding Customers}"
AlternatingRowBackground="AliceBlue"
AutoGenerateColumns="False"
MaxHeight="250"
CanUserAddRows="False"
CanUserDeleteRows="False" >
<Custom:DataGrid.Columns>
<Custom:DataGridTemplateColumn>
<Custom:DataGridTemplateColumn.Header>
<WrapPanel>
<CheckBox IsChecked="{Binding Path=IsCheckAll, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},
UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock>Select<LineBreak/>UnSelect</TextBlock>
</WrapPanel>
</Custom:DataGridTemplateColumn.Header>
<Custom:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Selected, Mode=TwoWay}"/>
</DataTemplate>
</Custom:DataGridTemplateColumn.CellTemplate>
</Custom:DataGridTemplateColumn>
The usercontrol you try to find, is (I assume as it's not in the code snippet) in the logical tree.
The binding is in the template which means that it's part of the visual tree. As they don't have a connection you cannot find it.

Silverlight 3.0 and MVVM Pattern

i am working on this article here they are using Silverlight 4.
link text
but i am using Silverlight 3.but for button we are not able to find the command
Command="{Binding Path=DataContext.GetPerson, ElementName= LayoutRoot }"
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="53,112,0,0" Name="button1"
VerticalAlignment="Top" Width="75" Command="{Binding Path=DataContext.GetPerson, ElementName= LayoutRoot }"
CommandParameter="{Binding Path=Age, ElementName=hi}" />
so in Silverlight 3 what should i do to get this Command property for the button
any help would be great
A command is a bindable way of associating an action to a control (button for instance).
The command controls 2 things:
whether it can be executed
what to do when it's executed
by implementing the ICommand interface
They've been around for a while in WPF and were recently added to SL4
If you want your code to work in SL3 you'll have to bind the IsEnabled property to a property in your view model that has the same logic as the CanExecute implementation of the command
and to add a Click event handler for the button which has the same logic has the command's Execute
Also, this button passes a parameter to the command (CommandParameter), you'll have to handle passing this parameter manually
You could use a framework like prism, add the relevant dll's to your project, then add a reference to the top of page like so
xmlns:prism="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation"
Then declare the prison attribute on your button
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="53,112,0,0" Name="button1"
VerticalAlignment="Top" Width="75" Command="{Binding Path=DataContext.GetPerson, ElementName= LayoutRoot }"
prism:Click.Command={Binding SomeCommand}
prism:Click.CommandParameter="{Binding Path=Age, ElementName=hi}" />

Placing common contols in two tab pages

I have a tab item with 2 tab pages. I want to place 4 check boxes in each of the tab pages with all check boxes having the same property. How it can be done easily?
Bind all your checkboxes to the same property (from your ViewModel, you do have one, right?). Then they will all display the same information.
There's not much to the binding code.. You could try something like...
<TabControl>
<TabItem Header="Tab1">
<StackPanel>
<CheckBox Content="One" Checked="{Binding Path=MyProperty}"/>
<CheckBox Content="Two" Checked="{Binding Path=MyProperty}"/>
</StackPanel>
</TabItem>
<TabItem Header="Tab2">
<StackPanel>
<CheckBox Content="Three" Checked="{Binding Path=MyProperty}"/>
<CheckBox Content="Four" Checked="{Binding Path=MyProperty}"/>
</StackPanel>
</TabItem>
</TabControl>
..where MyProperty is a local property representing the state you want to show.

Resources