Silverlight & Blend try and encourage you to separate styles and structure in much the same way as you should with HTML and CSS. However, Blend can be confusing as it will offer up some properties to be changed but “hide” others. One example of this is the seemingly simple task of changing the colour of the text in a button. You’d be forgiven for thinking you can select the button and directly edit the foreground colour since the background is available. You must ignore this temptation, if you don’t attempt to make style changes directly to the structure (control) then you’ll avoid a lot of confusion. I’ve created a little tutorial to show one way of solving this;
- Create a new project in Blend and accept the defaults.
- Add a button
- Select the button, hint using the control tree is often more reliable, right-click and choose Edit Templatate->Edit a Copy. To promote separation I recommend saving the style to the Application. You should give the style a good name, but I’ll be naughty and leave it at ButtonStyle1
- You’ll now find yourself in the Template for the button. Ignore this and return the MainPage.xaml (there is a quicker way but lets keep things simple). Now you want to change the colour of the button, so you need to edit the buttons style. Select the Resources tab and click the button to edit ButtonStyle1
- Now switch back to the Properties tab and you can change the Foreground (remember to drag the little colour select from the bottom left of the selector).
- All done.
So the “take home” from this is don’t make style changes directly to your controls always look at changing the separate style xaml, not only will you have better separation but you’ll avoid a lot of frustration when trying to find the property you want to change.
Another quick bookmark of a blog that talks about an open source database project that could be ideal for Silverlight out-of-browser applications
Today I got a rude error message from my application when I attempted to do a very simple operation, that of removing an item from ListBox; "Operation not supported on read-only collection."
The problem stems from the fact that I’d bound my ListBox to an ObservableCollection, once bound the Items collection becomes read-only. A know some others have had the same problem so I thought I’d blog about my solution. Utilizing a function, I’d previously blogged about, to find the ListBoxItem from a button click I then do a little casting and the item is removed;
private void buttonDelete_Click(object sender, RoutedEventArgs e)
ListBoxItem selectedItem = FindAssociatedListBoxItem(sender);
// if we have found an item then remove it
if (selectedItem != null)
MyColl myColl = this.ListBoxProducts.ItemsSource as MyColl;
MyObject selectedObj = selectedItem.DataContext as MyObject;