Гость
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / INotifyPropertyChanged / 10 сообщений из 10, страница 1 из 1
19.01.2015, 11:49
    #38857378
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Не получается подписаться на событие. Делаю так

Составной контрол:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
<Style TargetType="{x:Type local:RotateControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:RotateControl}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid Background="Transparent">
                            <Grid RenderTransformOrigin=".5 .5">
                                <Grid.RenderTransform>
                                    <RotateTransform Angle="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Angle}"/>
                                </Grid.RenderTransform>
                                <Grid.Triggers>
                                    <EventTrigger RoutedEvent="Binding.TargetUpdated">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetProperty="(Grid.RenderTransform).(RotateTransform.Angle)"                             
                                                                 From="0" To="360" Duration="0:0:1"/>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </Grid.Triggers>
                            <Line  X1="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Radius}" 
                                   Y1="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Radius}" 
                                   Stroke="White" StrokeThickness="1">
                                <Line.X2>
                                    <MultiBinding Converter="{StaticResource XLineCoordConverter}" ConverterParameter="1" 
                                                  NotifyOnTargetUpdated="True">
                                        <Binding Path="X1" RelativeSource="{RelativeSource Self}"/>
                                        <Binding Path="House1"/>
                                        <Binding Path="House2"/>
                                    </MultiBinding>
                                </Line.X2>
                                <Line.Y2>
                                    <MultiBinding Converter="{StaticResource YLineCoordConverter}" ConverterParameter="1">
                                        <Binding Path="X1" RelativeSource="{RelativeSource Self}"/>
                                        <Binding Path="House1"/>
                                        <Binding Path="House2"/>
                                    </MultiBinding>
                                </Line.Y2>
                            </Line>
                      </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>



Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
    <Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Grid Margin="100 70 0 0">
            <local:RotateControl x:Name="rtc1" Panel.ZIndex="1" 
                                 Width="{Binding ElementName=window,  Path=ActualHeight, Converter={StaticResource SizeConverter}}" 
                                 Height="{Binding ElementName=window,  Path=ActualHeight, Converter={StaticResource SizeConverter}}" 
                                 Radius="{Binding ElementName=window,  Path=ActualHeight, Converter={StaticResource RadiusConverter}}" 
                                 Loaded="rtc1_Loaded" SizeChanged="rtc1_SizeChanged"/>
        </Grid>
        <StackPanel HorizontalAlignment="Right" Canvas.Right="80" Orientation="Vertical">
            <StackPanel Orientation="Horizontal">
                <TextBox x:Name="year" Width="40"></TextBox>
                <TextBox x:Name="month" Width="20"></TextBox>
                <TextBox x:Name="day" Width="20"></TextBox>
                <TextBox x:Name="hour" Width="20"></TextBox>
                <TextBox x:Name="min" Width="20"></TextBox>
                <TextBox x:Name="sec" Width="20"></TextBox>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBox x:Name="lat" Width="80" Text="55.75"></TextBox>
                <TextBox x:Name="lng" Width="80" Text="37.583333"></TextBox>
            </StackPanel>
            <ComboBox x:Name="cbHSys" Width="300" SelectedIndex="0"></ComboBox>
            <Button x:Name="GatData" Click="GatData_Click">Get data</Button>
            <ScrollViewer>
                <Label x:Name="julday"></Label>
            </ScrollViewer>
        </StackPanel>
    </Canvas>



Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
public partial class MainWindow : Window, INotifyPropertyChanged{
        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
private void GetData()
        {
            julday.Content = "";
            DateTime date = new DateTime(Convert.ToInt32(year.Text), Convert.ToInt32(month.Text), Convert.ToInt32(day.Text),
                                         Convert.ToInt32(hour.Text), Convert.ToInt32(min.Text), Convert.ToInt32(sec.Text));
            CircleModel model = CalcNatalChart(date);
            model.Radius = (this.ActualHeight - (this.ActualHeight > 150 ? 150 : 0)) / 2;
            this.ViewModel = model;
        }

        
        private void rtc1_Loaded(object sender, RoutedEventArgs e)
        {
            GetData();
        }
}



Дальше не пойму, что делать. Сам мой контрол вращается, но событие не пойму где и как поймать, чтобы забиндить новую измененную модель.
...
Рейтинг: 0 / 0
19.01.2015, 14:36
    #38857577
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Вроде немного разобрался, но есть одна проблема.

При выполнении события
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
        private void GetData()
        {
            julday.Content = "";
            DateTime date = new DateTime(Convert.ToInt32(year.Text), Convert.ToInt32(month.Text), Convert.ToInt32(day.Text),
                                         Convert.ToInt32(hour.Text), Convert.ToInt32(min.Text), Convert.ToInt32(sec.Text));
            CalcNatalChart(date);
            _model.Radius = (this.ActualHeight - (this.ActualHeight > 150 ? 150 : 0)) / 2;
            this.ViewModel = _model;
            ViewModel.RaisePropertyChanged(null);
        }



повешенного на кнопку, все работает, а вот на таймер нет:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
        private DispatcherTimer timer;
        void timer_Tick(object sender, EventArgs e)
        {
            julday.Content = "";
            CalcNatalChart(DateTime.Now);
            _model.Radius = (this.ActualHeight - (this.ActualHeight > 150 ? 150 : 0)) / 2;
            this.ViewModel = _model;
            ViewModel.RaisePropertyChanged(null);
        }
...
Рейтинг: 0 / 0
19.01.2015, 17:00
    #38857754
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Не обновляется View вообще. Всегда использует старое значение при автоматическом обновлении.
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
private void GetData()
        {
            julday.Content = "";
            SetCurDate();
            DateTime date = new DateTime(Convert.ToInt32(year.Text), Convert.ToInt32(month.Text), Convert.ToInt32(day.Text),
                                         Convert.ToInt32(hour.Text), Convert.ToInt32(min.Text), Convert.ToInt32(sec.Text));
            CalcNatalChart(date);
            _model.Radius = (this.ActualHeight - (this.ActualHeight > 150 ? 150 : 0)) / 2;
            this.ViewModel = _model;
        }



Кто-нибудь может сталкивался с таким?
...
Рейтинг: 0 / 0
19.01.2015, 17:19
    #38857796
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Pavluha,

ViewModel.RaisePropertyChanged(null);
нужно передавать параметры (имя обновляемого свойство к которому есть привязка)
...
Рейтинг: 0 / 0
20.01.2015, 06:04
    #38858028
Сон Веры Павловны
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Roman MejtesPavluha,

ViewModel.RaisePropertyChanged(null);
нужно передавать параметры (имя обновляемого свойство к которому есть привязка)
Не обязательно - при передаче string.Empty или null происходит оповещение об изменении всех свойств модели: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
Разумеется, по-хорошему надо передавать именно имя изменившегося свойства, но вышеприведенный код тоже должен работать.
Pavluhaповешенного на кнопку, все работает, а вот на таймер нет
А вы уверены, что у вас таймер вообще срабатывает?
MSDNTimers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
DispatcherTimer Class (System.Windows.Threading)
...
Рейтинг: 0 / 0
20.01.2015, 10:14
    #38858149
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Сон Веры Павловны,

Конечно срабатывает! Я же прежде чем задавать вопрос проверил все.
И если бы таймер не работал, то данные не обновлялись бы, но данные обновляются.
Я еще добавил TextBlock, на свой контрол и в нем данные обновляются, а вот другие объекты нет.
...
Рейтинг: 0 / 0
20.01.2015, 13:47
    #38858437
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Pavluha,

таймер выполняется же по идее в другом потоке, попробуйте через Dispatcher обновить
...
Рейтинг: 0 / 0
20.01.2015, 14:54
    #38858545
Сон Веры Павловны
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Roman MejtesPavluha,

таймер выполняется же по идее в другом потоке, попробуйте через Dispatcher обновить
не нужно здесь обновление через диспетчер:
Сон Веры ПавловныMSDNThis is because DispatcherTimer operations are placed on the Dispatcher queue like other operations.
DispatcherTimer Class (System.Windows.Threading)

Pavluha,
покажите, как у вас устанавливается DataContext, и что он из себя представляет.
...
Рейтинг: 0 / 0
20.01.2015, 16:38
    #38858685
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
Сон Веры Павловны,

Спасибо большое, все заработало.

Контекст установил в конструкторе:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
        public MainWindow()
        {
            InitializeComponent();

            SetCurDate();
            DataContext = ViewModel;
            ViewModel = _model;
        }


        void timer_Tick(object sender, EventArgs e)
        {
            julday.Content = "";
            CalcNatalChart(now); - ИДЕТ ПЕРЕРАСЧЕТ МОДЕЛИ
            now = now.AddMinutes(30);
            datetime.Text = now.ToLongDateString() + "   " + now.DayOfWeek + "   " + now.ToLongTimeString(); ;
        }
...
Рейтинг: 0 / 0
20.01.2015, 16:40
    #38858690
Pavluha
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
INotifyPropertyChanged
В модели сделал так:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
public class CircleModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        double _radius;
        public double Radius
        {
            get
            {
                return _radius;
            }
            set
            {
                if (_radius == value) return;
                _radius = value;
                OnPropertyChanged("Radius");
            }
        }

        double _angel;
        public double Angel
        {
            get
            {
                return _angel;
            }
            set
            {
                if (_angel == value) return;
                _angel = value;
                OnPropertyChanged("Angel");
            }
        }
        
        ...................
    }
...
Рейтинг: 0 / 0
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / INotifyPropertyChanged / 10 сообщений из 10, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]