Sql, Wpf, Xaml, C #, bind data, dynamic resource, access non-stationary data, get object reference
Ok, but I'm pretty pretty new to WPF and XAML, despite my searching, I couldn't find a simple solution and it seems to me that I won't be able to find an answer pretty soon.
The question is so simple that I created a WPF project and have a datagrid in SelectList.xaml. After selecting a row, I save the selected row in an object, naming that object "category". So far so good, but I can't figure out how am I going to get a reference to this object from somewhere else in temp.xaml?
Thanks a lot Any help would be much appreciated Cheers
source to share
A common way to provide indirect communication in WPF is to use the mediation pattern. You can use a pick to post your category selection and have the temp subscribe to a change notification for your category selection.
See http://www.eggheadcafe.com/tutorials/aspnet/ec832ac7-6e4c-4ea8-81ab-7374d3da3425/wpf-and-the-model-view-vi.aspx for a simple example of a specific mediator. There are also several popular MVVM frameworks that provide implementations of the Mediator patterns if you want a more robust implementation.
Simple mediation implementation:
public sealed class Mediator
{
private static Mediator instance = new Mediator();
private readonly Dictionary<string, List<Action<object>>> callbacks
= new Dictionary<string, List<Action<object>>>();
private Mediator() { }
public static Mediator Instance
{
get
{
return instance;
}
}
public void Register(string id, Action<object> action)
{
if (!callbacks.ContainsKey(id))
{
callbacks[id] = new List<Action<object>>();
}
callbacks[id].Add(action);
}
public void Unregister(string id, Action<object> action)
{
callbacks[id].Remove(action);
if (callbacks[id].Count == 0)
{
callbacks.Remove(id);
}
}
public void SendMessage(string id, object message)
{
callbacks[id].ForEach(action => action(message));
}
}
SelectList.xaml code:
private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
var category = e.AddedItems.FirstOrDefault() as Category;
if(category != null)
{
Mediator.Instance.SendMessage("Category Selected", category);
}
}
Temp.xaml code-behind:
public Temp()
{
InitializeComponent();
Mediator.Instance.Register
(
"Category Selected",
OnCategorySelected
);
}
private void OnCategorySelected(object parameter)
{
var selectedCategory = parameter as Category;
if(selectedCategory != null)
{
}
}
source to share