I have problem that i don't know how to bind data in windows phone 8 and the scenario is :-
I request data from server and after I got response I display them in grid and list boxes (like a table).
Until here every thing is okay after I finish the display function there is a new function that retrieves the update to last request.
Here is my problem:
When I receive the new data I don't know how bind this new data to same old table.
For example: the first request is return the gold price 1500$---> I display in table--->then new request--> the update function return the new price of gold is 1502$.
How to update desired row that have gold price textblock with the new price while the application running.
This the first request:-
public ObservableCollection<Data> DataReceivedCollection { get; set; }
private void FireRequest2()
{
var request = HttpWebRequest.Create(new Uri("http://74.54.46.178/vertexweb10/webservice.svc/getallsymbols?AccountID=1122336675")) as HttpWebRequest;
request.Method = "GET";
request.CookieContainer = cookieJar;
request.BeginGetResponse(ar =>
{
HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
using (var response = (HttpWebResponse)req2.EndGetResponse(ar))
{
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var outerRoot1 = JsonConvert.DeserializeObject<OuterRootObject1>(reader.ReadToEnd());
JArray jsonArray = JArray.Parse(outerRoot1.d);
JToken jsonArray_Item = jsonArray.First;
while (jsonArray_Item != null)
{
string Name = jsonArray_Item.Value<string>("Name");
string Bid = jsonArray_Item.Value<string>("Bid");
string Ask = jsonArray_Item.Value<string>("Ask");
string ID = jsonArray_Item.Value<string>("ID");
DataReceivedCollection = new ObservableCollection<Data>();
DispatchInvoke(() =>
{
myList.ItemsSource = DataReceivedCollection;
// and to add data you do it like this:
DataReceivedCollection.Add(new Data() { symid = ID, textFirst = Name, textSecond = Bid, textThird = Ask });
}
);
//Be careful, you take the next from the current item, not from the JArray object.
jsonArray_Item = jsonArray_Item.Next;
}
}
}
}
}, request);
}
And here is my XAML that i want to dsiaply the requested data from firerequest2();
<Grid Background="#FFC9DC97" x:Name="ContentPanel" Grid.Row="1" Margin="12,140,12,0">
<ListBox Name="myList" Background="#FFC9DC97">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="ide" Text="{Binding symid}" Grid.Column="3" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding textFirst}" Grid.Column="0" HorizontalAlignment="Left" Foreground="#FF1C69D8"/>
<TextBlock Text="{Binding textSecond}" Grid.Column="1" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding textThird}" Grid.Column="2" HorizontalAlignment="Right"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
To here every thing is working fine i don't know to update the grid with the new data from the next function
public class Data : INotifyPropertyChanged
{
private string _textFirst;
public string textFirst
{
[DebuggerStepThrough]
get { return _textFirst; }
[DebuggerStepThrough]
set
{
if (value != _textFirst)
{
_textFirst = value;
OnPropertyChanged("textFirst");
}
}
}
private string _textSecond;
public string textSecond
{
[DebuggerStepThrough]
get { return _textSecond; }
[DebuggerStepThrough]
set
{
if (value != _textSecond)
{
_textSecond = value;
OnPropertyChanged("textSecond");
}
}
}
private string _textThird;
public string textThird
{
[DebuggerStepThrough]
get { return _textThird; }
[DebuggerStepThrough]
set
{
if (value != _textThird)
{
_textThird = value;
OnPropertyChanged("textThird");
}
}
}
private string _symid;
public string symid
{
[DebuggerStepThrough]
get { return _symid; }
[DebuggerStepThrough]
set
{
if (value != _symid)
{
_symid = value;
OnPropertyChanged("symid");
}
}
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
Your dataReceived collection needs to be declared like this because it is the subject of a binding...
public ObservableCollection<Data> DataReceivedCollection { get; set; }
And in the initialization code, it needs to be instantiated like this...
DataReceivedCollection = new ObservableCollection<Data>();
And your data class should be declared something like this (not all properties declared)
public class Data : INotifyPropertyChanged
{
private string _textFirst;
public string TextFirst
{
[DebuggerStepThrough]
get { return _textFirst; }
[DebuggerStepThrough]
set
{
if (value != _textFirst)
{
_textFirst = value;
OnPropertyChanged("TextFirst");
}
}
}
private string _textSecond;
public string TextSecond
{
[DebuggerStepThrough]
get { return _textSecond; }
[DebuggerStepThrough]
set
{
if (value != _textSecond)
{
_textSecond = value;
OnPropertyChanged("TextSecond");
}
}
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
Doing these things will ensure that the binding engine gets the information it needs to populate your List Box.
This is only a start that will give you some better results. As mentioned in the commentary, your next port of call is to take up a study of INotifyPropertyChanged.
Related
I am developing a GUI where a user can connect to server and read the data. The data needs to be displayed on the GUI. For this I am using TabControl whose ContentTemplate is set to RichTextBox. The XAML code is as below
<TabControl x:Name="tabControl1" HorizontalAlignment="Stretch" MinHeight="50" Margin="0,0,0,0.2" Width="884"
ItemsSource="{Binding Titles, Mode=TwoWay}" Height="454" VerticalAlignment="Bottom">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<RichTextBox Margin="10" VerticalScrollBarVisibility="Visible" >
<FlowDocument>
<Paragraph FontSize="12" FontFamily="Courier New">
<Run Text="{Binding Content}"></Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
The background code for adding new tab and setting its header/content (static) is below
public class MainWindowVM : INotifyPropertyChanged
{
public MainWindowVM()
{
Titles = new ObservableCollection<Item>();
}
public class Item
{
public string Header { get; set; }
public string Content { get; set; }
}
public ObservableCollection<Item> Titles
{
get { return _titles; }
set
{
_titles = value;
OnPropertyChanged("Titles");
}
}
static int tabs = 1;
private ObservableCollection<Item> _titles;
private ICommand _addTab;
private ICommand _removeTab;
public ICommand AddTab
{
get
{
_addTab = new TabRelayCommand(
x =>
{
AddTabItem();
});
return _addTab;
}
}
public ICommand RemoveTab
{
get
{
_removeTab = new TabRelayCommand(
x =>
{
RemoveTabItem();
});
return _removeTab;
}
}
private void RemoveTabItem()
{
if (Titles.Count > 0)
{
Titles.Remove(Titles.Last());
tabs--;
}
}
public Item AddTabItem()
{
var header = "Log_" + tabs;
var content = "Content " + tabs;
var item = new Item { Header = header, Content = content };
Titles.Add(item);
tabs++;
OnPropertyChanged("Titles");
return item;
}
public void AddTabItem(string strFileName, string strContent)
{
var header = strFileName;
var content = strContent;
var item = new Item { Header = header, Content = content };
Titles.Add(item);
tabs++;
OnPropertyChanged("Titles");
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
However I need to set the content of the header dynamically (the data read from the socket). I can read the data I have it in string format.
Kindly suggest me how do I set the content of RichTextBox by appending the string.
I am new to C#. Thanks in advance
Edit:
After button click event, my application gets connected to the server. Also I start a parallel task which reads data from the socket.
Problem facing: Too much of CPU time taken (I can see upto 80 under Processes in Task Manager).
private void BtnConnect_Click(object sender, RoutedEventArgs e)
{
//connect
TCPClientClass tcpClient = TCPConnHandler.ConnectToService(tbIPAddress.Text);
if (tcpClient != null)
{
MessageBox.Show("Connected to " + tbIPAddress.Text);
//open new tab
var item = MainWindowVMObj.AddTabItem();
//now run a task to display the data in the tab
Thread thTabControl = new Thread(() =>
{
while (tcpClient.Connected)
{
String str = tcpClient.GetDataFromServer();
if (!String.IsNullOrEmpty(str))
tabControl1.Dispatcher.BeginInvoke((Action)(() => item.Content += str));
Thread.Sleep(200);
}
//item.Dispatcher.BeginInvoke
});
thTabControl.Start();
}
}
You could look up the Item to update in Titles and set its Content property.
For example, this sets the property of the first item (index 0) in the ObservableCollection<Item>:
Titles[0].Content += "append...";
The Item class should also implement INotifyPropertyChanged for you to see the changes without switching tabs:
public class Item : INotifyPropertyChanged
{
public string Header { get; set; }
private string _content;
public string Content
{
get { return _content; }
set { _content = value; OnPropertyChanged(nameof(Content)); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Help me please!!!
I have 3 UserControls
I select user on List Users UC listbox
Then send message from SendMessage UC to Database
when i send message to Db it must refresh my chat listBox in Correspondence UC, but problem is in my ChatWrapper.
PropertyChanged in ChatWrapper is always null, and I can't refresh my ListBox in Correspondence UC with new message
List Users:
public IEnumerable<EmployeesDb> getListNames
{
get { return Db.Instance.EmployeesDbs.ToList(); }
}
static EmployeesDb m_selectedUser;
public static EmployeesDb selectedUser
{
get { return m_selectedUser; }
set
{
if (value != null)
m_selectedUser = value;
Correspondence correspondence = new Correspondence();
correspondence.CorrespondenceChat();
}
}
}
Send Message ( I try to refresh -> SendInfo.FirstOrDefault().RefreshGUI();)
public static DependencyProperty SendInfoProperty =
DependencyProperty.Register(
"SendInfo",
typeof(IEnumerable<ChatWrapper>),
typeof(SendMessage));
public IEnumerable<ChatWrapper> SendInfo
{
get { return GetValue(SendInfoProperty) as IEnumerable<ChatWrapper>; }
set { SetValue(SendInfoProperty, value); }
}
void SendMessageCommandExecute()
{
//...
SendInfo.FirstOrDefault().RefreshGUI();
//...
}
ChatWrapper
public class ChatWrapper : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void FirePropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public void RefreshGUI()
{
FirePropertyChanged("message");
}
public ChatDb chatDb { get; set; }
public string message
{
get
{
return (chatDb != null) ? string.Format("{0} {1}.{2} / {3} / {4}\n{5}",
chatDb.FromEmployeesDb.surname,
chatDb.FromEmployeesDb.name[0],
chatDb.FromEmployeesDb.middleName[0],
chatDb.messageDateTime,
chatDb.computerName,
chatDb.message) : null;
}
}
Correspondence
//...
public partial class Correspondence : UserControl, INotifyPropertyChanged
{
public static DependencyProperty GetCorrespondenceInfoProperty =
DependencyProperty.Register(
"GetCorrespondenceInfo",
typeof(IEnumerable<ChatWrapper>),
typeof(Correspondence),
new PropertyMetadata(OnChanged));
public IEnumerable<ChatWrapper> GetCorrespondenceInfo
{
get { return GetValue(GetCorrespondenceInfoProperty) as IEnumerable<ChatWrapper>; }
set { SetValue(GetCorrespondenceInfoProperty, value); }
}
static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var me = d as Correspondence;
me.chat = me.GetCorrespondenceInfo;
}
ICollectionView m_CollectionView;
public static IEnumerable<ChatWrapper> m_chat;
public IEnumerable<ChatWrapper> chat
{
get { return m_chat; }
set
{
m_chat = value;
if (ListUsers.selectedUser != null)
CorrespondenceChat();
FirePropertyChanged("chat");
}
}
public void CorrespondenceChat()
{
if (m_chat == null)
return;
m_CollectionView = CollectionViewSource.GetDefaultView(m_chat);
//...
FirePropertyChanged("chat");
}
XAML of Correspondence (refresh
<Grid>
<ListBox x:Name="correspondenceListBox" ItemsSource="{Binding chat, RelativeSource={RelativeSource AncestorType={x:Type local:Correspondence}}}"
Height="auto" Grid.Row="0" Grid.Column="1" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding message}" TextWrapping="Wrap" Width="auto"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I tried to write
public event PropertyChangedEventHandler PropertyChanged = delegate { };
PropertyChanged is no longer null, but it's still not updated
I have a command which sends text when the send button is clicked. The binding is set to two way and the updatesource trigger to propertychanged. but the value of the textbox doesnt change to string.empty which is included in the sendCommand, even though the command was able to take the updated textbox value for a new message.
public class BuddyChatViewModel : BaseViewModel
{
private string chat;
public string Chat
{
get { return chat; }
set
{
chat = value;
RaisePropertyChanged();
}
}
public RelayCommand sendChatCommand { get; private set; }
string username = "";
string buddy = "";
UriStrings url = new UriStrings();
BuddiesHomeModel buddiesList = new BuddiesHomeModel();
HttpService http = new HttpService();
StorageService store = new StorageService();
string response = "";
BuddyChatModel buddyChat = new BuddyChatModel();
List<BuddyChat2Datum> buddychatList = new List<BuddyChat2Datum>();
BuddyChat2Datum tempDatum = new BuddyChat2Datum();
private ObservableCollection<BuddyChat2Datum> buddyChatOC = new ObservableCollection<BuddyChat2Datum>();
public ObservableCollection<BuddyChat2Datum> BuddyChatOC
{
get { return buddyChatOC; }
set
{
buddyChatOC = value;
RaisePropertyChanged();
}
}
private async void sendChatExecute()
{
int i = 0;
string s = url.buddychatText(username, buddy, chat);
chat = "";
response = await http.GetAsync(s);
buddyChat = JsonConvert.DeserializeObject<BuddyChatModel>(response);
buddychatList.Clear();
for (i = 0; i < buddyChat.data.Count; i++)
{
tempDatum.conversation = buddyChat.data[i].conversation;
tempDatum.datetime = buddyChat.data[i].datetime;
tempDatum.from = buddyChat.data[i].from;
tempDatum.to = buddyChat.data[i].to;
if (tempDatum.from == username)
tempDatum.isLeft = false;
else
tempDatum.isLeft = true;
buddychatList.Add(tempDatum);
tempDatum = new BuddyChat2Datum();
}
BuddyChatOC.Clear();
for (i = 0; i < buddychatList.Count; i++)
{
BuddyChatOC.Add(buddychatList[i]);
}
Navigate<BuddyChatViewModel>(buddychatList);
}
#region State Management
public override void LoadState(object navParameter, Dictionary<string, object> state)
{
sendChatCommand = new RelayCommand(sendChatExecute);
int i = 0;
base.LoadState(navParameter, state);
BuddyChatOC.Clear();
// load test items again; in production this would retrieve the live item by id or get it from a local data cache
List<BuddyChat2Datum> buddychatList = (List<BuddyChat2Datum>)navParameter;
//var mes = new MessageDialog(buddychatList.Count.ToString());
//await mes.ShowAsync();
for(i=0;i<buddychatList.Count;i++)
{
BuddyChatOC.Add(buddychatList[i]);
}
username = buddychatList[i-1].username;
buddy = buddychatList[i-1].buddy;
}
public override void SaveState(Dictionary<string, object> state)
{
base.SaveState(state);
}
#endregion
}
}
xaml code:
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<ListView x:Name="chatList" HorizontalAlignment="Stretch" ItemsSource="{Binding BuddyChatOC}" ItemTemplateSelector="{StaticResource ChatSelector}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
<RelativePanel Grid.Row="1" Margin="5,10,5,10">
<TextBox x:Name="sendtext" Margin="0,0,2,0" Text="{Binding Chat, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" RelativePanel.AlignLeftWithPanel="True" RelativePanel.LeftOf="sendtextbutton"/>
<Button x:Name="sendtextbutton" Content="Send" Command="{Binding sendChatCommand}" RelativePanel.AlignRightWithPanel="True" >
</Button>
</RelativePanel>
</Grid>
Implement INotifyPropertyChanged in BuddyChatViewModel.
public class BuddyChatViewModel : INotifyPropertyChanged, BaseViewModel
{
private string chat;
public string Chat
{
get { return chat; }
set
{
chat = value;
NotifyPropertyChanged("Chat");
}
}
//INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
If you're using MVVMLight (and from how this question is tagged I assume you do), you need to specify changed property name in RaisePropertyChanged call.
That should work in your case:
public string Chat
{
get { return chat; }
set
{
chat = value;
RaisePropertyChanged(() => Chat);
}
}
I am using Listview having datasource as observablecollection<empclass>
My overall class structure is like
Class empclass
{
command = new RelayCommand(myfunction, true);
private int _abc;
public int abc
{
get { return _abc;}
set { _abc = value;
onpropertychanged("abc")
}
private int _pqr;
public int pqr
{
get { return _pqr;}
set { _pqr = value;
onpropertychanged("pqr")
}
public void myfunction()
{
messagebox.show((abc+pqr).Tostring());
}
}
i have a separate button, where on click i want to invoke command of selected item to show addition of abc and pqr on respected values present in that object.
It would be great If you could help me with small code example.
Thanks
Ashpak
I'm assuming you have a ListView named lv:
<ListView Name="lv" ... </ListView>
Then you can bind to the SelectedItem of that ListView and use the item's command property.
<Button Command="{Binding ElementName=lv, Path=SelectedItem.command}">Button Text</Button>
Note that for this to work you have to have a public property command, e.g.:
Class empclass
{
public RelayCommand command {get;set;}
...
}
Try this:
1. XAML code:
<Window x:Class="SoButtonBindingHelpAttempt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:soButtonBindingHelpAttempt="clr-namespace:SoButtonBindingHelpAttempt"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<soButtonBindingHelpAttempt:MainViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding ObservableCollection}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type soButtonBindingHelpAttempt:Empclass}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"></ColumnDefinition>
<ColumnDefinition Width="120"></ColumnDefinition>
<ColumnDefinition Width="120"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding abc, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBlock>
<TextBlock Grid.Column="1" Text="{Binding pqr, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBlock>
<Button Grid.Column="2" Command="{Binding Command}" Content="Press me!"></Button>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid></Window>
2. ViewModel code Model code:
public class MainViewModel:BaseObservableObject
{
public MainViewModel()
{
ObservableCollection = new ObservableCollection<Empclass>(new List<Empclass>
{
new Empclass{abc=2, pqr = 3},
new Empclass{abc=5, pqr = 7},
new Empclass{abc=11, pqr = 13},
new Empclass{abc=17, pqr = 19}
});
}
public ObservableCollection<Empclass> ObservableCollection { get; set; }
}
public class Empclass : BaseObservableObject
{
private ICommand _command;
private int _abc;
private int _pqr;
public ICommand Command
{
get { return _command ?? (_command = new RelayCommand(myfunction)); }
}
public int abc
{
get { return _abc; }
set
{
_abc = value;
OnPropertyChanged("abc");
}
}
public int pqr
{
get { return _pqr; }
set
{
_pqr = value;
OnPropertyChanged("pqr");
}
}
private void myfunction()
{
//add you command logic here
var temp = pqr;
pqr = abc;
abc = temp;
}
}
3. MVVM parts implementation:
public class BaseObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
{
var propName = ((MemberExpression)raiser.Body).Member.Name;
OnPropertyChanged(propName);
}
protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
OnPropertyChanged(name);
return true;
}
return false;
}
}
public class RelayCommand<T> : ICommand
{
readonly Action<T> _execute;
readonly Func<T, bool> _canExecute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<T> execute, Func<T, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public void RefreshCommand()
{
var cec = CanExecuteChanged;
if (cec != null)
cec(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
if (_canExecute == null) return true;
return _canExecute((T)parameter);
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
}
public class RelayCommand : RelayCommand<object>
{
public RelayCommand(Action execute, Func<bool> canExecute = null)
: base(_ => execute(),
_ => canExecute == null || canExecute())
{
}
}
4. Look like this:
Regards
I request data from server and after I got response I display them in grid and list boxes -TextBlock(like a table).Until here every thing is okay I finish the display function after that i must call new URL and desirelized the new JSON data to update the my grid table value for example:- my small application request login first after login success i request new URL that retrieve items in (JSON array) with sell price and buy price ==> here i draw my grid with this data like table as i told you before finally i need request new URL retrieve just the items that changed on the server with new prices ===> i dont know how to search in my grid textblock table to update the desired row, please help me (Please check my code below they told me there is an error with INPC and the for loop because when i request the second URL two times the new data not updated in my table ---> Please Advice)
This the my code with only the second URL call i don't know how to implement the third call and how to search into my table at the run time:-
public ObservableCollection<Data> DataReceivedCollection { get; set; }
private void FireRequest2()
{
var request = HttpWebRequest.Create(new Uri("http://74.54.46.178/vertexweb10/webservice.svc/getallsymbols?AccountID=1122336675")) as HttpWebRequest;
request.Method = "GET";
request.CookieContainer = cookieJar;
request.BeginGetResponse(ar =>
{
HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
using (var response = (HttpWebResponse)req2.EndGetResponse(ar))
{
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var outerRoot1 = JsonConvert.DeserializeObject<OuterRootObject1>(reader.ReadToEnd());
JArray jsonArray = JArray.Parse(outerRoot1.d);
JToken jsonArray_Item = jsonArray.First;
while (jsonArray_Item != null)
{
string Name = jsonArray_Item.Value<string>("Name");
string Bid = jsonArray_Item.Value<string>("Bid");
string Ask = jsonArray_Item.Value<string>("Ask");
string ID = jsonArray_Item.Value<string>("ID");
DataReceivedCollection = new ObservableCollection<Data>();
DispatchInvoke(() =>
{
myList.ItemsSource = DataReceivedCollection;
// and to add data you do it like this:
DataReceivedCollection.Add(new Data() { symid = ID, textFirst = Name, textSecond = Bid, textThird = Ask });
}
);
//Be careful, you take the next from the current item, not from the JArray object.
jsonArray_Item = jsonArray_Item.Next;
}
}
}
}
}, request);
}
And here is my XAML:-
<Grid Background="#FFC9DC97" x:Name="ContentPanel" Grid.Row="1" Margin="12,140,12,0">
<ListBox Name="myList" Background="#FFC9DC97">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="ide" Text="{Binding symid}" Grid.Column="3" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding textFirst}" Grid.Column="0" HorizontalAlignment="Left" Foreground="#FF1C69D8"/>
<TextBlock Text="{Binding textSecond}" Grid.Column="1" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding textThird}" Grid.Column="2" HorizontalAlignment="Right"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Here is the INotifyPropertyChanged Class
public class Data : INotifyPropertyChanged
{
private string _textFirst;
public string textFirst
{
[DebuggerStepThrough]
get { return _textFirst; }
[DebuggerStepThrough]
set
{
if (value != _textFirst)
{
_textFirst = value;
OnPropertyChanged("textFirst");
}
}
}
private string _textSecond;
public string textSecond
{
[DebuggerStepThrough]
get { return _textSecond; }
[DebuggerStepThrough]
set
{
if (value != _textSecond)
{
_textSecond = value;
OnPropertyChanged("textSecond");
}
}
}
private string _textThird;
public string textThird
{
[DebuggerStepThrough]
get { return _textThird; }
[DebuggerStepThrough]
set
{
if (value != _textThird)
{
_textThird = value;
OnPropertyChanged("textThird");
}
}
}
private string _symid;
public string symid
{
[DebuggerStepThrough]
get { return _symid; }
[DebuggerStepThrough]
set
{
if (value != _symid)
{
_symid = value;
OnPropertyChanged("symid");
}
}
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
Please help me
In this fragment...
DataReceivedCollection = new ObservableCollection<Data>();
DispatchInvoke(() =>
{
myList.ItemsSource = DataReceivedCollection;
// and to add data you do it like this:
DataReceivedCollection.Add(new Data() { symid = ID, textFirst = Name, textSecond = Bid, textThird = Ask });
}
You are destroying all previous data by reinitializing the DataReceivedCollection. So it is empty. Then in the dispatcher thread you are binding to it, and then adding to it. And you are repeating the whole thing all over on each pass or the while (jsonArray_Item != null) loop.
The observable collection and binding should be set once, at initialization time. Not each and every time you pass through a loop. If you want to set the collection to empty, use `DataReceivedCollection.Clear();
Move these lines to one-time initialization...
DataReceivedCollection = new ObservableCollection<Data>();
myList.ItemsSource = DataReceivedCollection;
Moreover, since you are dispatching the 'Add' (which is correct), you are inviting a closure problem, i.e., variables may be out of scope before the dispatcher thread executes.
Move these lines into the dispatcher thread...
string Name = jsonArray_Item.Value<string>("Name");
string Bid = jsonArray_Item.Value<string>("Bid");
string Ask = jsonArray_Item.Value<string>("Ask");
string ID = jsonArray_Item.Value<string>("ID");
Your implementation of INPC looks good. At this point it's just your logic flow that needs adjustment.